合并2个对象数组以创建对象图

时间:2017-02-20 10:20:55

标签: javascript angularjs arrays json

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

{
  "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

关于如何以正确的方式做到这一点的任何想法?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

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

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