猿问

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 中执行此操作吗?


大话西游666
浏览 379回答 3
3回答

湖上湖

您可以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);

跃然一笑

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

慕的地8271018

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), {});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答