我有两个objectcs数组
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的数组将ID重命名为新键。
让result = a.concat(b)会给我一个错误的结果
答案 0 :(得分:2)
您可以使用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()
答案 1 :(得分:2)
您可以使用echo ls -l | sh
# Passes the output of "echo ls -l" to the shell,
#+ with the same result as a simple "ls -l"
来获取唯一的ID,然后可以在其上进行映射,找到匹配的数据并以所需的格式构建对象:
Set
答案 2 :(得分:1)
forEach
循环可以使用,我们可以相应地分配值
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
}
]
var arr=[];
var k=admin.forEach((e)=>{
var a=e.categoryId;
if(e.teamName)
{
e.categoryName=e.teamName;
delete e.teamName;
}
if(e.id)
e.adminid=e.id;
else
e.id=null
e.memberId=null;
delete e.id
var t=member.forEach((x)=>{
if(x.categoryId==a)
e.memberId=x.id;
})
arr.push(e);
})
console.log(arr)