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

153
Vistas
What is the most efficient way to update a key inside of an array of objects in Javascript?

If I have a JavaScript array including 10 objects with the following syntax:

const myArray = [{Age: 10, Name: Justin}, {Age: 15, Name: Bob}, ..., {Age: 20, Name: Jon}];

What's the most efficient way to update the Name key to be DisplayName. This is my currently logic:

myArray = myArray.map(item=>{return {age:item.age, displayName:item.name }}); 
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I think your logic is fine but can be shortened.

myArray = myArray.map(({ age, name }) => ({ age, displayName: name })); 
about 4 years ago · Juan Pablo Isaza Denunciar

0

It can be done by shallow copy and use spread operator to rename key of object

const arr = [{Age: 10, Name: 'Justin'}, {Age: 15, Name: 'Bob'}, {Age: 20, Name: 'Jon'}];

function renameKey(obj, oldName, newName) {
  const { [oldName]: val, ...rest } = obj
  return {
    ...rest,
    [newName]: obj[oldName]
  }
}

const res = arr.map(i => {
  const tmp = renameKey(i, 'Name', 'displayName')
  return tmp
})

console.log('result ~> ', res)

or with lodash

const arr = [{Age: 10, Name: 'Justin'}, {Age: 15, Name: 'Bob'}, {Age: 20, Name: 'Jon'}];
const res = _.map(arr, function(i) {
  return _.mapKeys(i, function(val, key) {
    return key === 'Name' ? 'displayName' : key
  })
})

console.log('res ~> ', res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you want to update the original Array, never use map. Because map is used to create a new Array from an existing one.

Instead loop through the nodes in Array. Create tehe new node with key displayName and delete the key Name.

Working Fiddle

const myArray = [{Age: 10, Name: 'Justin'}, {Age: 15, Name: 'Bob'}, {Age: 20, Name: 'Jon'}];
myArray.forEach((node) => {
  node.displayName = node.Name;
  delete node.Name;
});
console.log(myArray);

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