2

How do i convert this:

{one:1,two:2,three:3,four:4}

to this:

{1:'one',2:'two',3:'tree',4:'four'}

I tried this :

Array.prototype.reverse.call({1:'one', 2:'two', 3:'tree',4:'four' length:5});

but this reverses the whole thing , which i dont want. Any one has any suggestions?

3 Answers3

1

You can combine Object.fromEntries() with Object.entries() and Array.prototype.map to reverse the key value pairs.

const obj = {one:1,two:2,three:3,four:4};

const reverseObj = Object.fromEntries(Object.entries(obj).map(([key, value]) => [value, key]));

console.log(reverseObj);
Reyno
  • 6,119
  • 18
  • 27
0

You could use a for... in loop to do this, assigning the key at each property to the value in the resulting object.

    
let o = {one:1,two:2,three:3,four:4};
let result = {};
for(let key in o) {
    result[o[key]] = key;
}
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

You could also use Array.reduce along with Object.entries() to get the result you wish:

    
let o = {one:1,two:2,three:3,four:4};
let result = Object.entries(o).reduce((acc, [key,value]) => { 
    return { ...acc, [value]: key };
}, {});
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

You can use Object.entries() to get key/value pairs into an array, and then .reduce() to construct a new object:

function invertObject(obj) {
  return Object.entries(obj).reduce(function(newObj, pair) {
    newObj[pair[1]] = pair[0];
    return newObj;
  }, {});
}
Pointy
  • 405,095
  • 59
  • 585
  • 614