gpt4 book ai didi

javascript - 在对象javascript数组中插入对象

转载 作者:行者123 更新时间:2023-11-30 19:50:20 24 4
gpt4 key购买 nike

我有两个对象数组:

{
"records": [
{
"lead_id": 97195,
"user_id": 613,
"segment_id": 0,
"email_address": "asdf@lkasd.asd",
"full_name": "asdf asdf",
},
{
"lead_id": 97197,
"user_id": 613,
"segment_id": 0,
"email_address": "asdfasdfasdf@asdasdasd.com",
"full_name": "asdf asdf",
}
]
}

第二个对象数组:

  {
"userTags": [
{
"lead_id": 97195,
"user_tag_id": 93,
"tag_name": "Julien",
},
{
"lead_id": 97195,
"user_tag_id": 93,
"tag_name": "test123"
},
{
"lead_id": 97197,
"user_tag_id": 93,
"tag_name": "General Business"
},
{
"lead_id": 97197,
"user_tag_id": 93,
"tag_name": "PAREB CLRB"
}
]
}

我想在特定的 lead_id 对象上插入标记名,例如在记录中有 "lead_id": 97195 和 userTags "lead_id": 97195,这是我的捕捉器或提示,应该连接到该对象数组,但我不知道如何将 tag_name 对象插入 records 列表

示例输出

"records": [
{
"lead_id": 97195,
"user_id": 613,
"segment_id": 0,
"email_address": "asdf@lkasd.asd",
"full_name": "asdf asdf",.
"tag_name": "Julien",
}]

最佳答案

您可以使用 mapfind 遍历您的记录并添加您在 中找到的 tag_name 字段userTags 对象。

但是,对于同一个 lead_id,您似乎有多个 tag_name。我添加了两个示例,一个采用第一个匹配的 lead_idtag_name,另一个收集所有匹配的 lead_id 的所有 tag_name :

const records = {
"records": [
{ "lead_id": 97195, "user_id": 613, "segment_id": 0, "email_address": "asdf@lkasd.asd", "full_name": "asdf asdf" },
{ "lead_id": 97197, "user_id": 613, "segment_id": 0, "email_address": "asdfasdfasdf@asdasdasd.com", "full_name": "asdf asdf" }
]
};

const userTags = {
"userTags": [
{ "lead_id": 97195, "user_tag_id": 93, "tag_name": "Julien" },
{ "lead_id": 97195, "user_tag_id": 93, "tag_name": "test123" },
{ "lead_id": 97197, "user_tag_id": 93, "tag_name": "General Business" },
{ "lead_id": 97197, "user_tag_id": 93, "tag_name": "PAREB CLRB" }
]
};

const newRecords = {
records: records.records.map(record => {
const lead_id = record.lead_id;
const tag = userTags.userTags.find(tag => tag.lead_id === lead_id);
return { ...record, tag_name: tag.tag_name };
})
};

const newRecordsMult = {
records: records.records.map(record => {
const lead_id = record.lead_id;
const tags = userTags.userTags
.filter(tag => tag.lead_id === lead_id)
.map(tag => tag.tag_name);
return { ...record, tag_name: tags };
})
}

console.log(newRecords, newRecordsMult);

关于javascript - 在对象javascript数组中插入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54552037/

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