JS,字典列表到列表字典,基于键

时间:2019-10-25 03:46:16

标签: javascript node.js dictionary

我有一个字典列表,其中包含一些属性,例如一个url和有关该url的一些信息:

[{
    url:"https://example1.com/a"
    something:"ABC"
},{
    url:"https://example1.com/b"
    something:"DEF"
},{
    url:"https://example2.com/c"
    something:"GHI"
},{
    url:"https://example2.com/d"
    something:"JKL"
}]

现在,我想将其拆分为一个列表字典,根据url分组。对于以上内容,我的目标数据结构是这样的:

{
    "example1.com" : [{
        url:"https://example1.com/a"
        something:"ABC"
    },{
        url:"https://example1.com/b"
        something:"DEF"
    }],
    "example2.com" : [{
        url:"https://example2.com/c"
        something:"GHI"
    },{
        url:"https://example2.com/d"
        something:"JKL"
    }]
}

在python中,这可以使用itertools包以及一些列表理解技巧来实现,但我需要在javascript / nodejs中实现。

有人可以引导我正确的方向来使用javascript吗?

干杯。

3 个答案:

答案 0 :(得分:1)

index  time          app_v   last     source   currency   created_at
1      2019-10-23    3       4488     gol      JPY        66
2      2019-10-23    29193   6687     gol      JPY        65

答案 1 :(得分:1)

您可以在数组对象上使用reduce方法。

let data = [{
    url:"https://example1.com/a",
    something:"ABC"
},{
    url:"https://example1.com/b",
    something:"DEF"
},{
    url:"https://example2.com/c",
    something:"GHI"
},{
    url:"https://example2.com/d",
    something:"JKL"
}];

let ret = data.reduce((acc, cur) => {
  let host = cur['url'].substring(8, 20); // hardcoded please use your own 
  if (acc[host])
    acc[host].push(cur);
  else
    acc[host] = [cur];
  return acc;
}, {})

console.log(ret);

答案 2 :(得分:1)

list.reduce((groups, item) => {
    let host = new URL(item.url).hostname;
    (groups[host] || (groups[host] = [])).push(item);
    return groups;
}, {});

如果您喜欢简短的内容。

或更短

list.reduce((g, i) => (i.host = new URL(i.url).hostname, (g[i.host] || (g[i.host] = [])).push(i), g), {});