lodash属性在数组和嵌套子数组中搜索 [英] lodash property search in array and in nested child arrays

查看:535
本文介绍了lodash属性在数组和嵌套子数组中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组:

[
    {
        id: 1,
        name: 'test 1',
        children: []
    },
    {
        id: 2,
        name: 'test 2',
        children: [
            {
                id: 4,
                name: 'test 4'
            }
        ]
    },
    {
        id: 3,
        name: 'test 3',
        children: []
    }
]

如何在此数组嵌套<$ c中按 id 属性进行过滤$ c> children arrays?

How can I filter by the id property in both this array and the nested children arrays?

例如,搜索 id = 3 ,应返回 test 3 对象,并搜索 id = 4 应返回测试4 object。

For example, searching for id = 3, should return the test 3 object, and searching for id = 4 should return the test 4 object.

推荐答案

使用lodash,您可以这样做:

Using lodash, you can do something like this:

_(data)
    .thru(function(coll) {
        return _.union(coll, _.pluck(coll, 'children'));
    })
    .flatten()
    .find({ id: 4 });

在这里,通过()用于初始化包装值。它返回原始数组和嵌套子类的并集。然后使用 flatten()展平此阵列结构,以便 find()项目。

Here, thru() is used to initialize the wrapped value. It's returning the union of the original array, and the nested children. This array structure is then flattened using flatten(), so you can find() the item.

这篇关于lodash属性在数组和嵌套子数组中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆