gpt4 book ai didi

javascript - 合并 2 个具有相同主 ID 的数组

转载 作者:行者123 更新时间:2023-12-01 16:25:41 25 4
gpt4 key购买 nike

我想合并这两个具有相同 id (box_id) 的数组

const boxes = [
{ box_id: 1, box_name: "Box 1" },
{ box_id: 2, box_name: "Box 2" },
];

const box_settings = [
{ box_id: 1, box_name: "Box 1", box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 },
{ box_id: 1, box_name: "Box 1", box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 },
{ box_id: 2, box_name: "Box 2", box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 },
{ box_id: 2, box_name: "Box 2", box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 },
];

进入这个:

[
{
box_id: 1,
box_name: "Box 1",
box_settings: [
{ box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 },
{ box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 },
],
},
{
box_id: 2,
box_name: "Box 2",
box_settings: [
{ box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 },
{ box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 },
],
},
];

提前致谢。这些是由 MySQL 查询生成的数组。

最佳答案

您可以使用 map 返回预期的数组对象

const boxes = [
{ box_id: 1, box_name: "Box 1" },
{ box_id: 2, box_name: "Box 2" },
];
const box_settings = [
{ box_id: 1, box_name: "Box 1", box_settings_id: 1, box_number_of_people: 2, box_total_price: 368 },
{ box_id: 1, box_name: "Box 1", box_settings_id: 2, box_number_of_people: 4, box_total_price: 736 },
{ box_id: 2, box_name: "Box 2", box_settings_id: 3, box_number_of_people: 2, box_total_price: 400 },
{ box_id: 2, box_name: "Box 2", box_settings_id: 4, box_number_of_people: 4, box_total_price: 800 },
];

var result=boxes.map(x=>{
return {
box_id:x.box_id,
box_name:x.box_name ,
box_settings:(box_settings.filter(y=>y.box_id==x.box_id))
.map(a=> {
return{
box_settings_id:a.box_settings_id ,
box_number_of_people:a.box_number_of_people,
box_total_price:a.box_total_price
}
})
}
})
console.log(result);

关于javascript - 合并 2 个具有相同主 ID 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62103687/

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