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 }});
I think your logic is fine but can be shortened.
myArray = myArray.map(({ age, name }) => ({ age, displayName: name }));
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>
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);