【问题标题】:recursively filter json data for search bar递归过滤搜索栏的json数据
【发布时间】:2021-04-13 05:32:48
【问题描述】:

我正在尝试为反应表编写搜索栏过滤器。

困难的部分是JSON数据结构,它可能具有未知深度的父子关系,例如:

  data = [
    {
      input: "row 0 ",
      output: "output of the first row"
      subRows: [],
    },
    {
      input: "row 1",
      output: "output of the second row"
      subRows: [
        {
          input: "third row 1.0",
          output: "output of the 3° row"
          subRows: [
            {
              input: "row 1.0.0",
              output: "output of the third row"
              subRows: [],
            },
          ],
        },
        {
          input: "row 1.1",
          output: "output of 2 rows after the third (fifth)"
          subRows: []
        },
      ],
    },
  ];

附加信息:上述 JSON 的每个对象在我的 html(jsx) 表中都表示为一行,而他的 subRows 是其他行,可以通过用户单击来展开。

我认为我可以使用 ES6 过滤器功能来处理它,但我不知道如何。

如果用户在搜索栏中输入例如:“third”

,这就是我所期望的结果
        {
          input: "third row 1.0",
          output: "output of the 3° row"
          subRows: []
        },
        {
          input: "row 1.1",
          output: "output of 2 rows after the third (fifth)",
          subRows: []
        },

这是我的代码:

 const updateFilter = (filterValue) => {
   let results = data.filter(function f(row) {
      if (Object.values(row).includes(filterValue.toLowerCase())) {
        return true;
      }
      if (row.subRows && row.subRows.length > 0) {
        return (row.subRows = row.subRows.filter(f));
      }
    });
    console.log(JSON.stringify(results));
  };
 }

这里是codePen中的代码:https://codepen.io/ardiz90/pen/yLajjRQ?editors=0012

感谢您的帮助!

编辑:结果我无法展平行,因为表需要树结构中的数据才能呈现它,所以下面编写的展平行的解决方案是不可行的..

【问题讨论】:

    标签: javascript reactjs ecmascript-6 filter uisearchbar


    【解决方案1】:

    您可以先展平嵌套对象,然后相应地过滤值。我还认为您使用Object.values(...).includes(...) 的过滤机制将无法正常工作。

    这是一个展平对象并过滤它们的示例:

    // returns a Array containing the element itself and its children recursively
    function flattenWithSubRows(entries) {
        return entries.flatMap(entry => [
            entry, ...flattenWithSubRows(entry.subRows)
        ]);
    }
    
    // gets an array containing only the objects 
    // containing the searchString in a string property
    function getAllMatchingItems(searchString, array) {
        const isMatching = entry => Object.values(entry)
            .filter(val => typeof val === 'string')
            .map(val => val.toLowerCase())
            .some(val => val.includes(searchString.toLowerCase()));
    
        return flattenWithSubRows(array).filter(isMatching)
    }
    
    const filtered = getAllMatchingItems("third", data);
    console.log(filtered);
    

    【讨论】:

    • 我们也可以清空 flattenWithSubRows 中的 subRows 属性吗?否则我们会有重复的过滤值,对吧?
    • 是的,如果您不需要过滤数组中的实际 subRows,您绝对可以这样做
    猜你喜欢
    • 2018-12-24
    • 2023-03-31
    • 2021-11-28
    • 2021-01-13
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多