How to replace array of object property name in javascript

强颜欢笑 提交于 2021-02-08 11:01:41

问题


I need to replace array of object in javascript. Here is my data variable and I want to update data variable

const data = [{name: "poran", id: "22"}];

Expected value:

data = [{value: "poran", age: "22"}];

How can I replace array of object?


回答1:


You can create a new array with the use of .map() and some Object Destructuring:

const data = [{name:"poran",id:"22"}];

const result = data.map(({ name:value , id:age }) => ({value, age}));

console.log(result);



回答2:


You can use a .forEach() loop over the array:

data.forEach((obj) {
  obj.value = obj.name;
  obj.age = obj.id;
  delete obj.name;
  delete obj.id;
});

It's a little simpler if you just make a new array with .map(), but if you need to keep the old objects because there are lots of other properties, this would probably be a little less messy.




回答3:


try this:

const data = [{name:"poran",id:"22"}]
const rst = data.map(res=>({value: res.name, age: res.id}));

console.log(rst)


来源:https://stackoverflow.com/questions/57206060/how-to-replace-array-of-object-property-name-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!