Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!