【问题标题】:How to create a nested filter with lodash如何使用 lodash 创建嵌套过滤器
【发布时间】:2017-06-12 05:31:37
【问题描述】:

我有以下嵌套的 JSON 数据结构。每个节点可以有任意数量的子节点,并且数据可以是任意数量的深度节点。

[{
    id : "a",
    path : "a"
}, {
    id : "b",
    path : "b"
}, {
    id : "c",
    path : "c",
    children: [{
        id : "a",
        path : "c/a"
    }, {
        id : "b",
        path : "c/b",
        children: [{
            id : "a",
            path : "c/b/a"
        }, {
            id : "b",
            path : "c/b/b"
        }]
    }]
}]

我需要在 lodash (v3.10.1) 中创建一个函数,它返回匹配路径的嵌套 JSON 对象和任何父对象。 例如,如果我要搜索“b”,过滤器应返回以下内容:

[{
    id : "b",
    path : "b"
}, {
    id : "c",
    path : "c",
    children: [{
        id : "b",
        path : "c/b",
        children: [{
            id : "a",
            path : "c/b/a"
        }, {
            id : "b",
            path : "c/b/b"
        }]
    }]
}]

我最初的尝试是这样的,但它确实奏效了:

const filterTree = (filter, list) => {
    return _.filter(list, (item) => {
        if (item.path) {
            return _.includes(item.path.toLowerCase(), filter.toLowerCase());
        } else if (item.children) {
            return !_.isEmpty(filterTree(filter, item.children));
        }
    });
};

任何帮助将不胜感激

【问题讨论】:

标签: javascript json filter lodash


【解决方案1】:

第一个问题是if (item.path) 总是true,所以递归调用永远不会发生。

为了获得您想要的结果,您必须在递归情况下过滤后更新item.children,因为_.filter 不会改变您传递给它的数组。如果您不希望输入发生变异,请先使用_.cloneDeep 进行复制。

const data = [{"id":"a","path":"a"},{"id":"b","path":"b"},{"id":"c","path":"c","children":[{"id":"a","path":"c/a"},{"id":"b","path":"c/b","children":[{"id":"a","path":"c/b/a"},{"id":"b","path":"c/b/b"}]}]}];

const filterTree = (filter, list) => {
  return _.filter(list, (item) => {
    if (_.includes(_.toLower(item.path), _.toLower(filter))) {
      return true;
    } else if (item.children) {
      item.children = filterTree(filter, item.children);
      return !_.isEmpty(item.children);
    }
  });
};

console.log(filterTree('b', data));
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

【讨论】:

  • 谢谢@4castle,你是明星!
猜你喜欢
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
相关资源
最近更新 更多