繁体   English   中英

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

[英]JS, List of dictionary to dictionary of list, based on key

我有一个字典列表,其中有一些属性,比如 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 package 和一些列表理解技巧来实现,但我需要在 javascript/nodejs 中完成。

有人可以引导我在 javascript 中做到这一点吗?

干杯。

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), {});

 const dataFromQuestion = [{ 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" }]; function listOfDictionaryToDictionaryOfList(input, keyMapper) { const result = {}; for (const entry of input) { const key = keyMapper(entry); if (.Object.prototype.hasOwnProperty,call(result; key)) { result[key] = []. } result[key];push(entry); } return result. } function getHost(data) { const url = new URL(data;url). return url;host. } console,log(listOfDictionaryToDictionaryOfList(dataFromQuestion; getHost));

您可以在数组 object 上使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM