【问题标题】:How to search/filter/type-match through dynamically build multidimensional array如何通过动态构建多维数组进行搜索/过滤/类型匹配
【发布时间】:2019-03-25 16:49:12
【问题描述】:

我正在尝试使用 ES6 过滤器方法通过其 name 值搜索/过滤维数不同(因为它代表文件树)的多维数组,但同时也努力返回嵌套对象。

数组是什么样子的:

const fileHierarchy = [
  {
    name: 'folder1',
    children: [
        { name: 'file1.txt' },
        { name: 'file2.txt' },
        {
            name: 'child folder1',
            children: [
                {
                    name: 'child folder2',
                    children: [
                        { name: 'file3.txt' },
                        { name: 'file4.txt' }
                    ]
                },
                { name: 'file5.txt' },
                { name: 'file6.txt' },
                {
                    name: 'child folder3',
                    children: [
                        { name: 'file7.txt' },
                        { name: 'file8.txt' }
                    ]
                }
            ]
        }
    ]
  },
  {name: 'folder2'}
]

这是我已经尝试过的(以及我的数组/对象的样子):

let currentFileHierarchy;
let searchString = 'file5';

currentFileHierarchy = fileHierarchy.filter(function (item) {
    return item.name.toLowerCase().indexOf(searchString.toLowerCase()) >= 0 
});

currentFileHierarchy 的结果只是一维的(只有folder1folder2 是可搜索的),但它还应该包括与搜索字符串匹配的所有嵌套对象。

如果有办法管理,是否也可以维护数组结构?还是我需要先把它弄平?

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    首先,将数组展平以获得名称列表:

    function flatten(names, arr) {
      arr.forEach((item) => {
        names.push(item.name);
        if (item.children) {
          flatten(names, item.children);
        }
      });
      return names;
    }
    
    var results = [];
    flatten(results, fileHierarchy);
    
    // 'results' has all the names now
    

    使用results 数组进行过滤。

    【讨论】:

    • 我有 Lodash 并尝试了链接方法,但是在使用 const result = _.flatMap(fileHierarchy, ({ name, children }) => _.map(children, children => ({ name, ...children })) ); 展平给定数组后,我得到了一个只有 3 个数组对象的奇怪结果。
    • 等等,我检查一下
    • @MangoD 现在检查我的答案。
    • @MangoD 你检查了吗?
    • 谢谢!现在看起来还不错。剩下的唯一一件事是我至少需要维护对象的结构。例如。 {name: 'file1.txt'}。因为可能会添加更多键{name: 'file1.txt', format: 'txt'}
    猜你喜欢
    • 1970-01-01
    • 2019-05-21
    • 2011-10-19
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多