2

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?

2 Answers 2

7

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Is there any way to modify the key in place..?? I mean without creating another array...??
@p4avinash it is not possible to change a property name, but you can add a new property with the same value and delete the old one.
@p4avinash I updated the answer with another approach
2

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.