如何基于JavaScript中的条件将属性添加到对象的属性?

时间:2018-06-28 12:24:33

标签: javascript angular

我有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: { ... }
]

在这里,如果第二个数组score在每个对象数组的zc对象内匹配,我想从第一个数组添加properties

使用如下所示的传播运算符编写一段代码

  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);

但是出现编译时错误。我在哪里做错了?

2 个答案:

答案 0 :(得分:1)

您可以使用arrreduce创建临时对象。使用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);

答案 1 :(得分:1)

由于无法在对象属性名称(例如{ 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,因为散布运算符不能与子对象一起使用。)