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

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

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

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

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