在Lodash中不使用循环获取对象的父级

时间:2018-02-14 00:24:24

标签: javascript lodash

在lodash中是否有一种方法/函数可以获取特定宠物ID的对象的父级而无需编写可以遍历每个人/宠物的代码?

例如:_.getParent(people, pets.id => 11) // returns {"type":"Fish", "id":11}

let people = [
    {
        "name": "Jack",
        "pets": [
            { "type":"Frog", "id":23 },
            { "type":"Bird", "id":57 },
            { "type":"Fish", "id":11 }
        ]
    },
    {
        "name": "Dawn",
        "pets": [
            { "type":"Lion", "id":89 },
            { "type":"Duck", "id":51 }
        ]
    },
    {
        "name": "Anne"
    },
    {
        "name": "Josh",
        "pets": []
    }
]

1 个答案:

答案 0 :(得分:2)

例如,

_.filter(
    _.flatMap(people, 'pets'),
    t => t && t.id === 11
)