[英]how to add property to property to an object based on the condition in javascript?
我有2个数组,如下所示:
arr = [
{ "zc": 33004, "score": 32.61 },
{ "zc": 33005, "score": 88.51 },
...
]
arr2 = [
"type": "feature", properties: { "zc": 33004 }, geometry: { ... },
"type": "feature", properties: { "zc": 33005}, geometry: { ... },
"type": "feature", properties: { "zc": 33009}, geometry: { ... }
]
expected result = [
"type": "feature", properties: { "zc": 33004, "score": 32.61 }, geometry: { ... },
"type": "feature", properties: { "zc": 33005, "score": 88.51 }, geometry: { ... },
"type": "feature", properties: { "zc": 33009, "score": 0 }, geometry: { ... }
]
在这里,如果第二个数组zc
在每个对象数组的properties
对象内匹配,我想从第一个数组添加score
。
我正在使用扩展运算符编写一段代码,如下所示
arr.forEach(ele => {
arr2.forEach(element => {
element = {
...element,
...((ele.zipcode==element.properties.zipcode) ? {element.properties.scope: ele.zipcode} : {element.properties.scope: 0})
}
});
})
console.log(arr2);
但出现编译时错误。 我在哪里做错了?
您可以使用reduce
来为arr
创建一个临时对象。 使用zc
作为键,将score
作为值。 这将使检查zc
存在变得更加容易。
使用map
循环通过arr2
let arr = [{"zc":33004,"score":32.61},{"zc":33005,"score":88.51}] let arr2 = [{"type":"feature","properties":{"zc":33004},"geometry":{}},{"type":"feature","properties":{"zc":33005},"geometry":{}},{"type":"feature","properties":{"zc":33009},"geometry":{}}] let tempArr = arr.reduce((c, v) => Object.assign(c, {[v.zc]: v.score}), {}) let result = arr2.map(o => { o = {...o} //shallow copy the object o.properties = {...o.properties,score: tempArr[o.properties.zc] || 0} return o; }) console.log(result);
由于无法在对象属性名称(例如{ element.properties.scope: ... }
)内使用点,因此会出现编译错误。因此,应按以下步骤进行操作:
arr.forEach(arrElem =>
arr2.forEach(arr2Elem =>
arr2Elem.properties = {
...arr2Elem.properties,
...{
score: arrElem.zipcode === arr2Elem.properties.zipcode ? arrElem.score : 0
}
}
);
);
console.log(arr2);
但是,我认为这不是正确的方法。 我认为您应该使用find()
,如下所示:
arr2.forEach(arr2Elem =>
arr2Elem.properties = {
...arr2Elem.properties,
...{
score: (arr.find(arrElem => arrElem.zipcode === arr2Elem.properties.zipcode) || { score: 0 }).score
}
}
);
console.log(arr2);
(我没有直接更改arr2Elem
,但是我更改了它的属性properties
因为散布运算符不能与子对象一起使用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.