我有这个数组:
[
{
id: 1,
name: 'test 1',
children: []
},
{
id: 2,
name: 'test 2',
children: [
{
id: 4,
name: 'test 4'
}
]
},
{
id: 3,
name: 'test 3',
children: []
}
]
如何根据此数组和嵌套的id
数组中的children
属性进行过滤?
例如,搜索id = 3
,应返回test 3
对象,搜索id = 4
应返回test 4
对象。
答案 0 :(得分:30)
使用lodash,您可以执行以下操作:
_(data)
.thru(function(coll) {
return _.union(coll, _.pluck(coll, 'children'));
})
.flatten()
.find({ id: 4 });
此处,thru()用于初始化包装值。它返回原始数组和嵌套子项的并集。然后使用flatten()展平此数组结构,以便您find()项目。
答案 1 :(得分:3)
这是一项非常简单的tree traversal任务。解决问题的最简单方法是递归(链接到jsbin)。它将适用于任何深度(当然具有递归限制),并且它是最复杂的O(n)的最快方法之一:
function find(id, items) {
var i = 0, found;
for (; i < items.length; i++) {
if (items[i].id === id) {
return items[i];
} else if (_.isArray(items[i].children)) {
found = find(id, items[i].children);
if (found) {
return found;
}
}
}
}
要查找所有匹配项 - 略微修改的函数(上面的jsbin链接已更新):
function findAll(id, items) {
var i = 0, found, result = [];
for (; i < items.length; i++) {
if (items[i].id === id) {
result.push(items[i]);
} else if (_.isArray(items[i].children)) {
found = findAll(id, items[i].children);
if (found.length) {
result = result.concat(found);
}
}
}
return result;
}
答案 2 :(得分:2)
另一个library(tidyr)
mtcars %>%
group_by(vs=factor(vs), cyl=factor(cyl), am=factor(am)) %>%
summarize(lo = mpg %>% min,
hi = mpg %>% max) %>%
ungroup() %>%
complete(am, cyl, nesting(vs)) %>%
ggplot() +
geom_linerangeh(aes(y = am, colour=vs, xmin = lo, xmax = hi),
position = position_dodgev(height = 0.5)) +
facet_wrap(~cyl, ncol = 1) +
theme_bw()
选项,其中包含子键和无限级别。
lodash