gpt4 book ai didi

javascript - 合并 Node js中具有相同字段的两个数组

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:41 24 4
gpt4 key购买 nike

我有这样的数组

arr1 = [{
"_id": 1,
"item": "Pencil",
"color": "Red"
},{
"_id":2,
"item": "Pen",
"color": "Yellow"
},{
"_id": 3,
"item": "Pencil",
"color": "Green"
}]

arr2 = [{
"value":"Pencil",
"price":1000,
},{
"value":"Pen",
"price":1500,
}]

如何将 arr2 合并到 arr1 中,并以 arr2 中的“value”和 arr1 中的“price”作为键?从而得到如下结果

res = [{
"_id": 1,
"item": "Pencil",
"color": "Red",
"price": 1000
},{
"_id":2,
"item": "Pen",
"color": "Yellow",
"price": 1500
},{
"_id": 3,
"item": "Pencil",
"color": "Green",
"price": 1000
}]

最佳答案

您可以使用 map 。例如:

let arr3 = arr1.map((el1) => {
let found = arr2.find(el2 => el1.item == el2.value)
if (found)
el1.price = found.price
return el1
})

console.log(arr3)

关于javascript - 合并 Node js中具有相同字段的两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60408440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com