繁体   English   中英

如何减少 object 中的元素?

[英]How can I reduce elements in object?

我有一个像这样的 object:

result: 
     > rows:
       > 0: {key: Array(4), value: 3}
          > key: (4) ["Person", "2020-06-24", "Product, "00000000008"]
            value: 3
       > 1: {key: Array(4), value: 10}
          > key: (4) ["Person", "2020-06-25", "Product, "00000000009"]
            value: 10
       > 2: {key: Array(4), value: 10}
          > key: (4) ["Person", "2020-06-25", "Product, "00000000008"]
            value: 10

现在,我需要做的是减少对相同代码(例如 00000000008)的结果检查并对值求和,以获得:

(例如)

00000000008   value: 13

现在,我的问题是怎么做,我尝试先使用 map 然后使用 reduce,但我不明白如何检查相同的代码并对值求和。

我能怎么做?

我已经尝试过这种方式,但它不起作用:

res是 object 的值

let example = res.rows.map((element)=> {
        console.log("ELEMENT IS ", element)
        let example1 = element.key[3].reduce(function(element, v){
          if(ref.hasOwnProperty(v))
            element[ref[v]] += v;
          else {
            ref[v] = element.length;
            element.push(prev = v)
          }
          return element
        }, [])
      })
      console.log("element", element)

创建您自己的 hashmap 并对所有值循环一次结果 object

const hashmap = {};

rows.forEach(v => {
  hashmap[v.product] = (hashmap[v.product] || 0) + v.value;
});

// then are you able to access any product value on O(1)
const total = hashmap['00000000008'];

console.log({total});
// total: 13

Array.map方法对于数据转换很有用,但是如果您必须进行聚合,则主要是昂贵的,因为您还必须Array.filter非聚合值。

您可以改用Array.reduce (MDN)来构建您自己的 object:

 let result = { rows: [ { key: ["Person", "2020-06-24", "Product", "00000000008"], value: 3 }, { key: ["Person", "2020-06-25", "Product", "00000000009"], value: 10 }, { key: ["Person", "2020-06-25", "Product", "00000000008"], value: 10 } ] } let output1 = result.rows.reduce((acc, current) => { let key = current.key[3]; // adding value to the accumulator acc[key] = (acc[key] || 0) + current.value; return acc; }, {}); console.log(output1); let output2 = result.rows.reduce((acc, current) => { // check if key is already present let found = acc.find(v => v.key == current.key[3]) // if it is, update the current value if (found) { found.value += current.value; } // otherwise create a new one else { acc.push({ key: current.key[3], value: current.value }); } return acc; }, []); console.log(output2)

暂无
暂无

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

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