javascript - 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 中执行此操作吗?
干杯。
解决方案
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), {});
推荐阅读
- debugging - Azure API 管理跟踪和调试
- r - 为什么在使用多个选项卡时代码只能部分工作?
- javascript - 过滤日期数组(每天只允许输入一个日期)
- python - 为什么 fbchat 中的 client.listen 无法再次工作?
- sql - 从交易中计算余额
- c - 'gtk/gtk.h' 使用 makefile 构建 gtk 项目时找不到文件
- node.js - Mongoose 更新将虚拟填充保存到文档
- node.js - Mongoose 查询 MongoDB,对象内的 find() 对象
- godot - 实例化对象区域 2D 是否检测不到鼠标
- asp.net - 如何在 Blazor-Server-App 中使用 cshtml(Razor 页面)