gpt4 book ai didi

javascript - 如何插入数组或值的对象并传输到新数据

转载 作者:行者123 更新时间:2023-11-28 14:17:51 26 4
gpt4 key购买 nike

我有两个名为记录联系人的数据,两者都有不同的lead_id 。如果lead_id与此对象的编号相同,则表明它们将连接或插入并转换为新的newRecords

我制作了一个示例数据来作为示例。希望您能举个例子。

"records": [
{
"lead_id": 95173,
"user_id": 526,
"first_name": "Aaron",
"last_name": "De La Rosa",
},
{
"lead_id": 95972,
"user_id": 459,
"first_name": "Abba",
"last_name": "Lorenzo",
},
{
"lead_id": 95974,
"user_id": 459,
"first_name": "Abba",
"last_name": "Lorenzo",
}
]
"contacts": [
{
"lead_id": 95173,
"lead_contact_number_type_id": 1,
"lead_contact_number_id": 25,
"lead_contact_number": "+1 206-501-4581"
},
{
"lead_id": 95972,
"lead_contact_number_type_id": 1,
"lead_contact_number_id": 26,
"lead_contact_number": "+1 206-501-4582"
},
{
"lead_id": 95974,
"lead_contact_number_type_id": 1,
"lead_contact_number_id": 27,
"lead_contact_number": "+1 206-501-4583"
},
{
"lead_id": 95173,
"lead_contact_number_type_id": 1,
"lead_contact_number_id": 28,
"lead_contact_number": "+1 206-501-4584"
}
]

预期输出

"newRecords": [
{
"lead_id": 95173,
"user_id": 526,
"first_name": "Aaron",
"last_name": "De La Rosa",
"contact_details": [
{
"lead_id": 95173,
"lead_contact_number_type_id": 1,
"lead_contact_number_id": 25,
"lead_contact_number": "+1 206-501-4581"
},
{
"lead_id": 95173,
"lead_contact_number_type_id": 1,
"lead_contact_number_id": 28,
"lead_contact_number": "+1 206-501-4584"
}
]
},
{
"lead_id": 95972,
"user_id": 459,
"first_name": "Abba",
"last_name": "Lorenzo",
"contact_details": [
{
"lead_id": 95972,
"lead_contact_number_type_id": 1,
"lead_contact_number_id": 26,
"lead_contact_number": "+1 206-501-4582"
}
]
},
{
"lead_id": 95974,
"user_id": 459,
"first_name": "Abba",
"last_name": "Lorenzo",
"contact_details": [
{
"lead_id": 95974,
"lead_contact_number_type_id": 1,
"lead_contact_number_id": 27,
"lead_contact_number": "+1 206-501-4583"
}
]
}
]

示例代码

let newRecordsMultContacts = newRecordsMult.map(records => {
lead_id = records.lead_id;
numbers = contacts
.filter(number => number.lead_id === lead_id)
.map(number => number.lead_contact_number);
return { ...records, lead_contact_number: numbers, lead_contact_number_id: number.lead_contact_number_id, lead_contact_number_type_id: number.lead_contact_number_type_id };
})

最佳答案

您可以在此处应用 mapfilter 方法的组合。

应用 map 并添加通过匹配lead_id过滤的联系人作为每条记录的新contact_details字段。

下面的代码应该可以解决问题。

let newRecords = records.map((record) => {
record['contact_details'] = contacts.filter((contact) => record.lead_id === contact.lead_id);
return record;
});

关于javascript - 如何插入数组或值的对象并传输到新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56642136/

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