简体   繁体   English

合并2个对象数组以创建对象映射

[英]Merging 2 arrays of objects to create a Map of Objects

I'm receiving the following data in my JS from a WebService : 我正在从WebService的JS中接收以下数据:

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

What's the fastest way to create the following object as a result : 结果创建以下对象的最快方法是什么:

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

I'm actually doing multiple forEach to format the data myself, but i think it's pretty ugly and not efficient.. PS : the key for the result map is the customer Id 我实际上在做多个forEach来自己格式化数据,但我认为它很难看而且效率不高。PS:结果映射表的关键是客户ID

Any idea on how to do this the right way? 关于如何正确执行此操作的任何想法吗?

Thanks for your help ! 谢谢你的帮助 !

You could iterate the outer object's keys and then the inner arrays. 您可以迭代外部对象的键,然后迭代内部数组。 If an result object does not exist, create one with the wanted keys and zero values. 如果结果对象不存在,请使用所需键和零值创建一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM