1

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 }}); 
Mulan
  • 129,518
  • 31
  • 228
  • 259
uppal2665
  • 29
  • 3
  • `Array` is a built-in global. Do **not** name your variable, `Array`. Call it `myArray` or be more descriptive like `let people = [ ... ]` – Mulan Oct 06 '21 at 04:52
  • You can use simple for, for in and for each loops. The best is for each for arrays. – Developer Oct 06 '21 at 04:55

3 Answers3

1

I think your logic is fine but can be shortened.

myArray = myArray.map(({ age, name }) => ({ age, displayName: name })); 
Mulan
  • 129,518
  • 31
  • 228
  • 259
zmag
  • 7,825
  • 12
  • 32
  • 42
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>
nart
  • 1,508
  • 2
  • 11
  • 24
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);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • Why the never in bold? – ksav Oct 06 '21 at 04:45
  • @ksav because the objective of the user is to update the existing array. So he should **not** make use of `map` for that. Its purpose id to create new array and not update existing. – Nitheesh Oct 06 '21 at 04:53