Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 合并2个对象数组以创建对象贴图_Javascript_Angularjs_Arrays_Json - Fatal编程技术网

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

Javascript 合并2个对象数组以创建对象贴图,javascript,angularjs,arrays,json,Javascript,Angularjs,Arrays,Json,我正在从Web服务接收JS中的以下数据: { "fire": { "totalOccurence": 2, "statsByCustomer": [ { "idCustomer": 1, "occurence": 1 }, { "idCustomer": 2, "occurence": 1 } ] }, "flood": { "totalOc

我正在从Web服务接收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:{totaloccurrence:2,statsByCustomer:[{idCustomer:1,occurrence:1},{idCustomer:2,occurrence:1}]},flood:{totaloccurrence:1,statsByCustomer:[{idCustomer:1,occurrence:1}]},
结果={},
keys=对象。keys(数据);
键。forEach(函数(k){
数据[k].statsbycuster.forEach(函数(a){
如果(!result[a.idCustomer]){
结果[a.idCustomer]={};
键。forEach(函数(kk){
结果[a.idCustomer][kk]=0;
});
}
结果[a.idCustomer][k]+=a.accurrence;
});
});
控制台日志(结果)

。作为控制台包装器{max height:100%!important;top:0;}
我实际上在做多个forEach,你能告诉我们吗?使用递归函数访问任何级别的数据到目前为止你做了什么?请让OP分享努力。