javascript - 按键值重新组合数组中对象的有效方法
问题描述
我有一个对象数组。这些对象有两个道具:字符串类型的属性“标签”和一个数组的道具“检测”。我需要一个可以将相同标签的对象分组并合并相对数组的函数。
例如:
const list = [
{ label: 'cat', detections: ['a','b'] },
{ label: 'horse', detections: ['c','d'] },
{ label: 'cat', detections: ['e','f'] }
]
会成为:
const result = groupMergeByLabel(list)
// value logged would be => [
{ label: 'cat', detections: ['a','b','e','f'] },
{ label: 'horse', detections: ['c','d'] }
]
解决方案
你可以使用reduce
:
const list = [
{ label: 'cat', detections: ['a','b'] },
{ label: 'horse', detections: ['c','d'] },
{ label: 'cat', detections: ['e','f'] }
];
const result = list.reduce((res, {label, detections}) => {
const existing = res.find(x => x.label === label);
if (existing) {
existing.detections.push(...detections);
} else {
res.push({label, detections});
}
return res;
}, []);
console.log(result);
推荐阅读
- dependency-injection - Autofac 依赖注入 - 设置公共属性
- c# - 如何从 github 运行 ASP.NET Web api
- sweetalert - 如何在 js 变量中保存甜蜜的警报提示
- python - Python 3:如何将函数添加到库的 Python 类中?
- sql - 如何设计用于存储库存商店中项目的数据库?
- android - 使用自定义对话框类时如何修改文本并单击侦听器?
- java - 无法使用 Java 编辑 XSL 属性值
- amazon-web-services - 如何触发服务器的侦听器
- assembly - 当内核开发者想写汇编时,他们是写高层次的,然后用编译器转换,还是直接写汇编?
- django - 从 `views.py` 在 django 中动态创建模型