简体   繁体   中英

How can I reduce elements in object?

I have an object like this:

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

Now, what I need to do is to reduce this result checking for the same code (for example 00000000008) and sum the value, to obtain:

(for example)

00000000008   value: 13

Now, my problem is how to do, I have tried to use first a map and then a reduce, but I don't understand how can I check for the same code and sum the value.

How can I do?

I have tried in this way, but it doesn't work:

res is the object with the values

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)

create your own hashmap and loop over the result object once for all values

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

The Array.map method is useful for data transformations, but if you have to aggregate is mostly expensive because you have also to Array.filter the non-aggregated values.

You can use Array.reduce (MDN) instead in order to build your own 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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