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

133
Vistas
mapping keys of Object in javascript

I would like to change key names in such object:

const data = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4',
}

with those keys from map:

const map = {
'key1': 'change1',
'key4': 'change4'
}

Using code below:

const replacedKeysInData = Object.keys(data).map((key) => {
const keyFromMap = map[key] || key;
return { [keyFromMap]: data[key] }
})
console.log(replacedKeysInData);

I get:

[
{ change1: 'value1' },
{ key2: 'value2' },
{ key3: 'value3' },
{ change4: 'value4' }
]

The point is that I would like to have it in one object:

{ 
change1: 'value1',
key2: 'value2',
key3: 'value3',
change4: 'value4' 
}

I suppose it is simple, how can I do it? Thanks

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

you are using map which returns an array. I created an empty object and added the keys in a forEach

const data = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4',
}
const map = {
'key1': 'change1',
'key4': 'change4'
}

const replacedKeysInData ={} 
Object.keys(data).forEach((key) => {
const keyFromMap = map[key] || key;
replacedKeysInData[keyFromMap] = data[key]
})
console.log(replacedKeysInData);

about 4 years ago · Juan Pablo Isaza Denunciar

0

It doesn't have to be anything complicated. Just iterate over the object, swap keys, and delete the original.

const data={key1:"value1",key2:"value2",key3:"value3",key4:"value4"},map={key1:"change1",key4:"change4"};

for (const key in data) {
  if (map[key]) {
    data[map[key]] = data[key];
    delete data[key];
  }
}

console.log(data);

about 4 years ago · Juan Pablo Isaza Denunciar

0

const data = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4',
}

const map = {
  'key1': 'change1',
  'key4': 'change4'
}

const replacedKeysInData = Object.entries(data).map(val => {
  if (Object.keys(map).includes(val[0])) {
    return [map[val[0]], val[1]]
  } else {
    return val
  }
});

const newData = Object.fromEntries(replacedKeysInData);

console.log(newData)

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