简体   繁体   English

具有对象数组的JS数组-组和总和属性

[英]JS Array with arrays of objects - Group and sum properties

I have this one array with multiple arrays in it, containing objects (responses from HTTP requests) 我有一个带有多个数组的数组,其中包含对象(来自HTTP请求的响应)

The big array: 大数组:

datas = [
   [
     {
       data: {
         pid: 107,
         value: 5
       }
       status: 200
     },
     {
       data: {
          pid: 108,
          value: 42
       }
     }
   ],
   [
     {
       data: {
         pid: 107,
         value: 64
       }
       status: 200
     },
     {
       data: {
          pid: 108,
          value: 322
       }
     }
   ]
]

Ok, so how could I make a new array (or object) grouped by pid and a sum with values assigned to pid? 好吧,那我怎样才能创建一个新的数组(或对象),该数组按pid和分配给pid的值求和? It is not the typical question with a SUM by property inside array of arrays. 在数组内部使用SUM by属性不是典型的问题。

What I have tried: 我尝试过的

 datas.forEach((d,k1) => { 
   d.forEach((e,k2) => {
   total += e.data.value
   newArr[k2] = total;
  })
})

You could use Array.prototype.reduce with an inner Array.prototype.forEach to iterate over the inner arrays and group PIDs into an Object : 您可以将Array.prototype.reduce与内部Array.prototype.forEach一起使用,以遍历内部数组并将PID分组为Object

 const data = [ [ { data: { pid: 107, value: 5 }, status: 200 }, { data: { pid: 108, value: 42 } } ], [ { data: { pid: 107, value: 64 }, status: 200 }, { data: { pid: 108, value: 322 } } ] ]; const merged = data.reduce((merged, innerArr) => { innerArr.forEach(({data}) => { merged[data.pid] = (merged[data.pid] || 0) + data.value; }); return merged; }, {}); console.log(merged); 

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

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