Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
How do I reverse the Object in Javascript

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

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; }

about 4 years ago · Juan Pablo Isaza Report

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;
  }, {});
}
about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!