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

时间:2019-01-18 08:39:48

标签: javascript

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

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" },
       ]
   },
]

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

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

但是结果是完全错误的,我得到了很多第一个contact : test的副本。

2 个答案:

答案 0 :(得分:4)

您可以使用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; }

答案 1 :(得分:3)

您可以像这样使用Setconst 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"},]},] /* > Get array of options > flatten them > get array of contact_linked_id > Get unique ids */ ,filteredIds = new Set(filtered_contacts.flatMap(a => a.options) .map(a => a.contact_linked_id)); console.log(contacts.filter(a => filteredIds.has(a.id)))

flatMap

如果您的浏览器中还没有filteredIds = new Set([].concat(...filtered_contacts.map(a => a.options)) .map(a => a.contact_linked_id)); supported,请使用:

headptr