问题
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