Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

reverse key and value in object js

//The concise way by using ES6 syntax like this.

const obj = {A : 1, B : 2, C : 3, D : 4}
 function objectFlip(obj) {
     return Object.entries(obj).reduce((acc, [key, value]) => (acc[value] = key, acc), {})
 }
console.log('input:  ',obj);
console.log('output: ',objectFlip(obj));



static objectFlip(obj) {
  const ret = {};
  Object.keys(obj).forEach(key => {
    ret[obj[key]] = key;
  });
  return ret;
}
//Or using Array.reduce() & Object.keys()

static objectFlip(obj) {
  return Object.keys(obj).reduce((ret, key) => {
    ret[obj[key]] = key;
    return ret;
  }, {});
}
//Or using Array.reduce() & Object.entries()

static objectFlip(obj) {
  return Object.entries(obj).reduce((ret, entry) => {
    const [ key, value ] = entry;
    ret[ value ] = key;
    return ret;
  }, {});
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #reverse #key #object #js
ADD COMMENT
Topic
Name
7+6 =