1
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?

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.