我有两个具有相同news_ids但属性不同的对象数组,我只是想知道如何组合它们并获得一个新的对象数组?
例如:
let arr1 = [{
news_id: 1,
title: "title1"
},
{
news_id: 2,
title: "title2"
},
{
news_id: 3,
title: "title3"
},
{
news_id: 4,
title: "title4"
},
]
let arr2 = [{
news_id: 3,
count: 3
},
{
news_id: 4,
count: 4
}
]
我想得到:
[
{news_id: 1, title: "title1", count: 0},
{news_id: 2, title: "title2", count: 0},
{news_id: 3, title: "title3", count: 3},
{news_id: 4, title: "title4", count: 4}
]
最佳答案
您可以使用forEach
和filter
进行以下操作:
arr1.forEach(i => i.count = (arr2.find(j => j.news_id == i.news_id) || { count: 0 }).count)
请在下面尝试。
let arr1 = [{
news_id: 1,
title: "title1"
},
{
news_id: 2,
title: "title2"
},
{
news_id: 3,
title: "title3"
},
{
news_id: 4,
title: "title4"
},
]
let arr2 = [{
news_id: 3,
count: 3
},
{
news_id: 4,
count: 4
}
]
arr1.forEach(i => i.count = (arr2.find(j => j.news_id == i.news_id) || { count: 0 }).count);
console.log(arr1);
关于javascript - 如何在JavaScript中将两个不同的对象数组合并为一个新的对象数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52833209/