如何在嵌套对象数组中搜索字段名称?

问题描述 投票:0回答:1

我正在寻找几种不同的方法来访问下面的数据,使用 ES6 和/或 lodash。

我想做的是返回父对象,其中 device_id 匹配。

即,对于实体中的每个项目,如果在任何嵌套对象中,device_id 字段 = abc,则返回整个数组项目

const entities = [
    {
        "<unknown key>": {
            "entity_id": "something",
            "device_id": "abc"
        },
        "<unknown key>": {
            "entity_id": "else",
            "device_id": "abc"
        },
    },
    {
        "<unknown key>": {
            "entity_id": "hello",
            "device_id": "xyz"
        },
        "<unknown key>": {
            "entity_id": "world",
            "device_id": "xyz"
        }
    }
]
javascript arrays lodash
1个回答
0
投票

Array#filter
Array#some
结合使用以获得所有匹配项。如果只需要一场匹配,请将
filter
替换为
find

let search = 'abc';
const entities=[{"<unknown key>":{entity_id:"something",device_id:"abc"},"<unknown key2>":{entity_id:"else",device_id:"abc"}},{"<unknown key>":{entity_id:"hello",device_id:"xyz"},"<unknown key2>":{entity_id:"world",device_id:"xyz"}}];
const res  = entities.filter(o => Object.values(o)
                .some(x => x.device_id === search));
console.log(res);

© www.soinside.com 2019 - 2024. All rights reserved.