newbie
newbie

Reputation: 1571

Grouping array of objects into nested maps

var map = new Map();
[ { serverid: '21312412521312',
    userid: '32523523412123',
    text: 'a',
    name: 'foo' },
  { serverid: '21312412521312',
    userid: '32523523412123',
    text: 'b',
    name: 'bar' }].forEach(x => {
    map.set(x.serverid, new Map());
    (map.get(x.serverid)).set(x.userid, [x.name, x.text])
});

map ends up as:
Map { '21312412521312' => Map { '32523523412123' => ['bar', 'b'] } } why does this happen? I expected it to end up as:
Map { '21312412521312' => Map { '32523523412123' => ['foo', 'a'], ['bar', 'b'] } }

Please do keep in mind this is only an example there will be more objects in the array. I'm trying to group them by serverid and userid in maps. Where am I going wrong?

Upvotes: 1

Views: 27

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

You need a third nested array or Set in order to contain multiple possible values for one userid, else your .set(x.userid ... will erase whatever previously existed at that userid index (which, here, is the a / foo on the second iteration).

var map = new Map();
[{
    serverid: '21312412521312',
    userid: '32523523412123',
    text: 'a',
    name: 'foo'
  },
  {
    serverid: '21312412521312',
    userid: '32523523412123',
    text: 'b',
    name: 'bar'
  }
].forEach(x => {
  if (!map.has(x.serverid)) map.set(x.serverid, new Map());
  const serverMap = map.get(x.serverid);
  if (!serverMap.has(x.userid)) serverMap.set(x.userid, []);
  serverMap.get(x.userid)
    .push([x.name, x.text]);
});
// look in browser console, not in the snippet console, to see the structure:
console.log(map);

Upvotes: 1

Related Questions