I have an array of objects -
const obj = [{name:'josh', city:'Sydney'},{name:'alice', city:'York'}]
I want to change 'city' property to 'town'. How can I make this change to the property of each object in the array?
CodePudding user response:
Using Array#map
:
const arr = [ { name: 'josh', city: 'Sydney' }, { name: 'alice', city: 'York' } ];
const res = arr.map(({ city, ...e }) => ({ ...e, town: city }));
console.log(res);
Using Array#forEach
:
const arr = [ { name: 'josh', city: 'Sydney' }, { name: 'alice', city: 'York' } ];
arr.forEach(e => {
e.town = e.city;
delete e.city;
});
console.log(arr);
CodePudding user response:
You can't do this directly, but what you can do is this:
const obj = [{name:'josh', city:'Sydney'},{name:'alice', city:'York'}]
for (let element of obj){
element.town = element.city;
delete element.city;
}