我正在从WebService的JS中接收以下数据:

{
  "fire": {
    "totalOccurence": 2,
    "statsByCustomer": [
      {
        "idCustomer": 1,
        "occurence": 1
      },
      {
        "idCustomer": 2,
        "occurence": 1
      }
    ]
  },
  "flood": {
    "totalOccurence": 1,
    "statsByCustomer": [
      {
        "idCustomer": 1,
        "occurence": 1
      }
    ]
  }
}


结果创建以下对象的最快方法是什么:

{
  "1": {
    "fire": 1,
    "flood": 1
  },
  "2": {
    "fire": 1,
    "flood": 0
  }
}


我实际上在做多次forEach来自己格式化数据,但是我认为这很丑陋而且效率不高。
PS:结果图的关键是客户ID

关于如何正确执行此操作的任何想法吗?

谢谢你的帮助 !

最佳答案

您可以迭代外部对象的键,然后迭代内部数组。如果结果对象不存在,请使用所需键和零值创建一个。



var data = { fire: { totalOccurence: 2, statsByCustomer: [{ idCustomer: 1, occurence: 1 }, { idCustomer: 2, occurence: 1 }] }, flood: { totalOccurence: 1, statsByCustomer: [{ idCustomer: 1, occurence: 1 }] } },
    result = {},
    keys = Object.keys(data);

keys.forEach(function (k) {
    data[k].statsByCustomer.forEach(function (a) {
        if (!result[a.idCustomer]) {
            result[a.idCustomer] = {};
            keys.forEach(function (kk) {
                result[a.idCustomer][kk] = 0;
            });
        }
        result[a.idCustomer][k] += a.occurence;
    });
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 合并2个对象数组以创建对象映射,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42341925/

10-12 12:25
查看更多