最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to change property name in array of objects in Javascript? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Dec 27, 2021 at 12:36 Majed Badawi 28.5k4 gold badges30 silver badges55 bronze badges asked Dec 27, 2021 at 12:32 KashyapKashyap 1051 gold badge4 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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);

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;
}
发布评论

评论列表(0)

  1. 暂无评论