过滤嵌套数组

时间:2017-06-23 08:14:11

标签: javascript arrays reactjs

我正在使用文本搜索某些数据。有些数据是嵌套的,而另一部分则不是。

  1. 如果它从数据的嵌套部分返回结果,它应该只返回嵌套的值(以及它的父值)。
  2. 我也把它放在codeSandbox上 - https://codesandbox.io/s/Q0w16jLP0

    功能:

    function filterTypes(items, search) {
      return items.filter(items => {
        const nestedName = items.typechild.map(x => x.name.toLowerCase());
        const name = items.name.toLowerCase();
        return search.every(x => {
          return name.includes(x) || nestedName.some(v => v.includes(x));
        });
      });
    }
    

    数据结构:

    {
        "name": "Food",
        "typechild": [{
            "name": "Fruit", "id":12,
        }, {
            "name": "Vegetable", "id":13,
        }]
    }
    

    现在如何运作:

    • 它会返回Food的所有子项。

    期望的结果:

    如果过滤器的值为Fruit,则应返回...

    • Food作为标题
    • Fruit低于该标题

    所需的数据结构

    {
        "name": "Food",
        "typechild": [{
            "name": "Fruit", "id":12,
        }]
    }
    

2 个答案:

答案 0 :(得分:0)

我会使用递归方法:

function check(el,name){
 if(el.name.includes(name)){
  return [el];
 }
 if(el.typechild && el.typechild.find){
 var child=el.typechild.find(function(child){
   return check(child,name);
 });
}
 if(child){
  child=check(child,name);
  child.unshift(el);
  return child;
}
return false;
}

它会返回

[Food Object, Fruit Object]

答案 1 :(得分:0)

改变原始数据的解决方案。



var data = [{ name: "Food", typechild: [{ name: "Fruit", level: 2, color: "#fff" }, { name: "Vegetable", level: 2, color: "#fff" }] }, { name: "Entertainment", typechild: [{ name: "Book", level: 2, color: "#fff" }, { name: "Movie", level: 2, color: "#fff" }, { name: "Bar", level: 3, color: "#fff" }] }, { name: "Misc", typechild: [{ name: "Foo", level: 2, color: "#fff" }] }],
    search = 'Fruit',
    index = data.length,
    temp;

while (index--) {
    temp = data[index].typechild.filter(o => o.name === search);
    if (temp.length) {
        data[index].typechild = temp;
    } else {
        data.splice(index, 1);
    }
}

console.log(data);

.as-console-wrapper { max-height: 100% !important; top: 0; }