javascriptarraysjavascript-objects

How to Iterate through a grouped object in JavaScript


I have an array of grouped objects, but I'm unable to iterate through and achieve the desired result.

[ 000000010: [
  {
    "userId" : "000000010",
    "played" : 10,
    "lost" : 5,
    "date" :"2019-04-01T00:00:00.000Z" 
    },
  {
    "userId" : "000000010",
    "played": 15,
    "lost" : 0,
    "date" :"2019-04-02T00:00:00.000Z" 
    }, 
],
000000020: [
  {
    "userId" : "000000020",
    "played": 11,
    "lost" : 4,
    "date" :"2019-04-01T00:00:00.000Z" 
    },
  {
    "userId" : "000000020",
    "played": 15,
    "lost" : 0,
    "date" :"2019-04-02T00:00:00.000Z" 
    }, 
]

]

I want to eliminate all possible duplicates and group all similar objects as follows

    {
    "userId" : "000000010",
    "played": 30,
    "lost" : 5,
    },
  {
    "userId" : "000000020",
    "played": 26,
    "lost" : 6,
    }, 

I have tried

Object.entries() 

but it returned

[obeject: object]

I have also tried

const allResults = {}
Object.keys(result).forEach(function(key) {
    let chats = result[key].chats;
          allResults[chats] = allResults[chats] ? allResults[chats] + 1 : 1;
  });

But I get undefined


Solution

  • If you are looking to sum the played and lost fields you should use reduce to merge the objects, summing the required fields. Then convert the array of entries back into an object.

    Try this

    const inputData = {
       "000000010":[
          {
             "userId":"000000010",
             "played":10,
             "lost":5,
             "date":"2019-04-01T00:00:00.000Z"
          },
          {
             "userId":"000000010",
             "played":15,
             "lost":0,
             "date":"2019-04-02T00:00:00.000Z"
          }
       ],
       "000000020":[
          {
             "userId":"000000020",
             "played":11,
             "lost":4,
             "date":"2019-04-01T00:00:00.000Z"
          },
          {
             "userId":"000000020",
             "played":15,
             "lost":0,
             "date":"2019-04-02T00:00:00.000Z"
          }
       ]
    };
    
    
    const result = Object.entries(inputData).map(([key, values]) => {
        const merged = values.reduce((accum, x) => { 
            accum.played += x.played; 
            accum.lost += x.lost; 
            return accum; 
        }, {"userId": key, "played": 0, "lost": 0});
        return [key, merged];
    });
    
    console.log(Object.fromEntries(result));
    

    Node prints the following

    {
      '000000010': { userId: '000000010', played: 25, lost: 5 },
      '000000020': { userId: '000000020', played: 26, lost: 4 }
    }