Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda