gpt4 book ai didi

javascript - 如何在javascript中基于相同的键和值合并两个对象数组?

转载 作者:行者123 更新时间:2023-12-05 00:34:28 25 4
gpt4 key购买 nike

我有两个数组视频和 storeProducts。视频数组可能有 product_id 并且 storeProducts 必须有
产品 ID。我需要基于两个 produt_id 合并这些,否则仅将视频项推送到数组中。

     let videos = [
{
"id": 1,
"product_id":"training_video_test_1",
"video_title": "Video title 1",
"video_short_description": "desc 1"
},
{
"id": 2,
"product_id":"training_video_test_2",
"video_title": "Video title 2",
"video_short_description": "desc 2"
},
{
"id": 3,
"product_id":"training_video_test_3",
"video_title": "Video title 3",
"video_short_description": "desc 3"
}

];

let storeProducts = [
{
"product_id":"training_video_test_1",
"prduct_title":"training_video_test_1",
"price":100
},
{
"product_id":"training_video_test_2",
"prduct_title":"training_video_test_2",
"price":100
}
];
我需要在 storeProducts.product_id === videos.product_id 时合并这两个否则忽略商店产品项目仅推送视频项目。
示例输出:
[
{
"id": 1,
"product_id":"training_video_test_1",
"video_title": "Video title 1",
"video_short_description": "desc 1",
"prduct_title":"training_video_test_1",
"price":100
},
{
"id": 2,
"product_id":"training_video_test_2",
"video_title": "Video title 2",
"video_short_description": "desc 2",
"prduct_title":"training_video_test_2",
"price":100
},
{
"id": 3,
"product_id":"training_video_test_3",
"video_title": "Video title 3",
"video_short_description": "desc 3"
}
]
我试过这样:
let resultArr = [];
videos.forEach((v)=>{
storeProducts.forEach((p)=>{
if(p.product_id == v.product_id){
resultArr.push(Object.assign({},v,p))

}
})
})
但它不像我预期的那样工作。请帮助我。

最佳答案

您可以使用map反而

let videos = [
{ id: 1, product_id: "training_video_test_1", video_title: "Video title 1", video_short_description: "desc 1" },
{ id: 2, product_id: "training_video_test_2", video_title: "Video title 2", video_short_description: "desc 2" },
{ id: 3, product_id: "training_video_test_3", video_title: "Video title 3", video_short_description: "desc 3" },
];

let storeProducts = [
{ product_id: "training_video_test_1", prduct_title: "training_video_test_1", price: 100 },
{ product_id: "training_video_test_2", prduct_title: "training_video_test_2", price: 100 },
];

const result = videos.map(v => ({ ...v, ...storeProducts.find(sp => sp.product_id === v.product_id) }));

console.log(result);

关于javascript - 如何在javascript中基于相同的键和值合并两个对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63616406/

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