gpt4 book ai didi

javascript - 数组和嵌套子数组中的 lodash 属性搜索

转载 作者:可可西里 更新时间:2023-11-01 01:21:41 24 4
gpt4 key购买 nike

我有这个数组:

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

如何在这个数组 嵌套的 children 数组中按 id 属性进行过滤?

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

最佳答案

使用 lodash,你可以做这样的事情:

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

在这里,thru()用于初始化包装值。它返回原始数组和嵌套子数组的联合。然后使用 flatten() 将此数组结构展平, 所以你可以 find()项目。

关于javascript - 数组和嵌套子数组中的 lodash 属性搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30714938/

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