我正在尝试根据某些条件向对象添加2个属性: 例如:
var data= [
{ name:"Jan", score:4, scale:4 },
{ name:"Feb",score:8, scale:3 },
{ name: "Mar", score:2, scale:9 },
{ name: "Apr", score:10, scale:1 }
]
data.map(function(point) {
if (some condition) {
point.m = {
a: 2
}
}else {
point.m = {
a: 10
}
}
})
//so result in the data im expecting to add the prop `m` of type object to the array.
data = [
{ name:"Jan", score:4, scale:4,m:{a:2} },
{ name:"Feb",score:8, scale:3,m:{a:2} },
{ name: "Mar", score:2, scale:9,m:{a:10} },
{ name: "Apr", score:10, scale:1,m:{a:2} }
]
现在在不同的比例上我想为道具m
添加另一个字段,我正在做:
point.m = {
b: 10 // this value is dynamic so could change.
}
所以我期待:
data = [
{ name:"Jan", score:4, scale:4,m:{a:2, b:10} },
{ name:"Feb",score:8, scale:3,m:{a:2, b:10} },
{ name: "Mar", score:2, scale:9,m:{a:10, b:10} },
{ name: "Apr", score:10, scale:1,m:{a:2, b:10} }
]
但由于某种原因,它只需要将最后一个字段添加到道具中。我得到结果:
data = [
{ name:"Jan", score:4, scale:4,m:{ b:10} },
{ name:"Feb",score:8, scale:3,m:{ b:10} },
{ name: "Mar", score:2, scale:9,m:{ b:10} },
{ name: "Apr", score:10, scale:1,m:{b:10} }
]
我在这里缺少什么?
答案 0 :(得分:0)
这部分示例:
point.m = {
b: 10 // this value is dynamic so could change.
}
用新对象替换 point.m
。您想要将其与Object.assign
合并。
Object.assign(point.m, { b: 10 })
或者,您可以直接将b
分配给m
point.m.b = 10
答案 1 :(得分:0)
您正在重写该物业。
data.map(function(point) {
point.m = {};
if (some condition) {
point.m.a = 2;
} else {
point.m.a = 10;
}
}
if (some_other_condition) {
point.m.b = 10;
}
});