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?
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);
delete the old one.