gpt4 book ai didi

javascript - 无法返回深层对象中的特定项目

转载 作者:行者123 更新时间:2023-12-03 07:18:33 24 4
gpt4 key购买 nike

我有两个对象数组,定义如下:

联系人数组:

[
{ id: "1", name: "test"},
{ id: "2", name: "foo" },
{ id: "3", name: "june"},
{ id: "4", name: "may" }
]

filtered_contacts 数组:

[
{
id: "1",
options: [
{ option_id: "1", contact_linked_id: "2" },
{ option_id: "2", contact_linked_id: "4" },
]
},
{
id: "2",
options: [
{ option_id: "3", contact_linked_id: "1" },
]
},
]

我需要使用 contact_linked_id 字段提取包含在 filtered_contacts 中的 contacts,为此我编写了以下代码:

 var c = contacts.map(c => filtered_contacts.find(x => x.options.map(z => z.contact_linked_id == c.id)));

但是结果完全错了,我得到了很多份第一个contact : test

最佳答案

你可以拿一个Set并收集联系人,然后过滤数组。

var contacts = [{ id: "1", name: "test" }, { id: "2", name: "foo" }, { id: "3", name: "june" }, { id: "4", name: "may" }],
filtered_contacts = [{ id: "1", options: [{ option_id: "1", contact_linked_id: "2" }, { option_id: "2", contact_linked_id: "4" }] }, { id: "2", options: [{ option_id: "3", contact_linked_id: "1" }] }],
cSet = filtered_contacts.reduce(
(s, { options }) => options.reduce(
(t, { contact_linked_id: id }) => t.add(id),
s
),
new Set
),
result = contacts.filter(({ id }) => cSet.has(id));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 无法返回深层对象中的特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54250241/

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