gpt4 book ai didi

javascript - 如何合并嵌套对象数组的内容?

转载 作者:行者123 更新时间:2023-12-02 21:13:03 25 4
gpt4 key购买 nike

我有一个名为 allLeads 的对象数组,它存储数组中每个项目的 leadNameleadId 以及一个名为 Leads 的项目这是另一个对象数组。

但目前我从后端接收数据的方式是,leads 数组一次仅存储一个对象。我想为每个 leadIdleadName 合并此潜在客户数组

目前情况如何

const allLeads = [
{
leadName: "software development",
leadId: 123,
leads: [{ profile: "hello", url: "bye" }]
},
{
leadName: "software development",
leadId: 123,
leads: [{ profile: "lets", url: "go" }]
},
{
leadName: "business development",
leadId: 234,
leads: [{ profile: "dont", url: "try" }]
},
{
leadName: "business development",
leadId: 234,
leads: [{ profile: "other", url: "side" }]
}
];

我想要怎样

const allLeads = [
{
leadName: "software development",
leadId: 123,
leads: [{ profile: "hello", url: "bye" }, { profile: "lets", url: "go" }]
},
{
leadName: "business development",
leadId: 234,
leads: [{ profile: "dont", url: "try" }, { profile: "other", url: "side" }]
}
];

最佳答案

const allLeads = [
{
leadName: "software development",
leadId: 123,
leads: [{ profile: "hello", url: "bye" }]
},
{
leadName: "software development",
leadId: 123,
leads: [{ profile: "lets", url: "go" }]
},
{
leadName: "business development",
leadId: 234,
leads: [{ profile: "dont", url: "try" }]
},
{
leadName: "business development",
leadId: 234,
leads: [{ profile: "other", url: "side" }]
}
];
function handle(array) {
let obj = array.reduce((acc, cur) => {
acc[cur.leadId] = acc[cur.leadId] || {};
acc[cur.leadId].leads = acc[cur.leadId].leads || [];
acc[cur.leadId].leadName = cur.leadName;
acc[cur.leadId].leadId = cur.leadId;
acc[cur.leadId].leads.push(...cur.leads);
return acc;
}, {});
return Object.values(obj);
}
console.log(handle(allLeads))

关于javascript - 如何合并嵌套对象数组的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61041759/

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