将对象数组分组到嵌套地图中

时间:2018-07-22 00:28:55

标签: javascript dictionary

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的最终结果是:
Map { '21312412521312' => Map { '32523523412123' => ['bar', 'b'] } }  为什么会这样?我希望它最终会变成:
 Map { '21312412521312' => Map { '32523523412123' => ['foo', 'a'], ['bar', 'b'] } }

请记住,这只是一个示例,数组中将有更多对象。我正在尝试通过地图中的serverid和userid对它们进行分组。 我要去哪里错了?

1 个答案:

答案 0 :(得分:1)

您需要一个 third 嵌套数组或Set才能包含一个userid的多个可能值,否则您的.set(x.userid ...将删除以前在该用户ID索引(此处为第二次迭代中的a / foo)。

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