javascript - es6 将两个数组与对象合并并累积数据
问题描述
我有两个对象数组
const a = [
{
"categoryId": 1,
"categoryName": "category 1",
"id": 11
},
{
"categoryId": 2,
"teamName": "category 2",
"id": 22
}
]
const b = [
{
"categoryId": 2,
"categoryName": "category 2",
"id": 33
},
{
"categoryId": 3,
"categoryName": "category 3",
"id": 44
}
]
现在我想将它们合并在一起,最终结果应该如下所示:
const result = [
{
"categoryId": 1,
"categoryName": "category 1",
"aId": 11,
"bId" null:
},
{
"categoryId": 2,
"categoryName": "category 2",
"aId": 22,
"bId" 33:
},
{
"categoryId": 3,
"categoryName": "category 3",
"aId": null,
"bId" 44:
}
]
我看不到如何分配空值。
我已经用 Object.assign 和 "..." 运算符尝试过,但没有得到想要的结果。
同样,我想根据数组将 id 重命名为新键。
let result = a.concat(b) 会给我一个错误的结果
解决方案
您可以使用contat()
将数组合并在一起,然后reduce()
通过其键删除重复的对象:
const admin = [
{
"categoryId": 66,
"categoryName": "category 66",
"id": 204
},
{
"categoryId": 149,
"teamName": "category 149",
"id": 178
}
]
const member = [
{
"categoryId": 66,
"teamName": "category 66",
"id": 271
},
{
"categoryId": 68,
"teamName": "category 68",
"id": 264
}
];
const client = [
{
"categoryId": 66,
"teamName": "category 66",
"id": 271
},
{
"categoryId": 155,
"teamName": "no team",
"id": 264
}
];
const merge = function(...params) {
let mergeResult = [];
params.map(elem => {mergeResult = mergeResult.concat(elem); });
return mergeResult;
}
const result = Object.values(merge(member, admin, client).reduce((acc,cur)=>Object.assign(acc,{[cur.categoryId]:cur}),{}));
console.log(result);
如果您需要更改重复的过滤条件,只需cur.categoryId
在Object.assign()
函数中更改
推荐阅读
- python - jupyter notebook 中“expected an indented block”错误的解决方案
- python - Python 屏幕截图,只有桌面背景(MacBook Catalina)
- detection - 表示边界框坐标的方法是什么?
- python - 用于覆盖序列化程序类的 save() 方法时,user.save() 无法正常工作
- python - 如何在 python 中从 MySql 获取列表?
- c# - 我可以在 .NET Core SignalR 中省略 Clients.All.SendAsync() 的“等待”吗?
- javascript - 如何禁用自动打开 jquery ui 月份选择器?
- sql - 按字母、数字、特殊字符顺序排序
- java - 如何通过 Java 高级别的客户端在 Elastic Search 中使用多个字段进行搜索
- ghostscript - 将 postscript 文件页面发送到不同的托盘