lodash属性在数组和嵌套子数组中搜索

时间:2015-06-08 16:54:32

标签: javascript underscore.js lodash

我有这个数组:

[
    {
        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对象。

3 个答案:

答案 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