首页 > 解决方案 > JS,字典列表到列表字典,基于键

问题描述

我有一个字典列表,其中有一些属性,比如一个 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 中执行此操作吗?

干杯。

标签: javascriptnode.jsdictionary

解决方案


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

单线(虽然很神秘)

data.reduce((g, i, _1, _2, h = new URL(i.url).hostname) => ((g[h] || (g[h] =[])).push(i), g), {});

推荐阅读