Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda