筛选器不适用于第三个子级别(嵌套级别)

时间:2019-07-17 06:44:17

标签: javascript typescript

我正在尝试过滤嵌套级别为3的数组。我必须在最后一级过滤该数组。

array = [{
    children: [{
        children: [{
            children: [],
            id: 2694,
            name: "Some Random data"
        }, {
            children: [],
            id: 2695,
            name: "Another Random Data"
        }],
        id: 2574,
        name: "Test data",
    }],
    id: 2530,
    name: "Main Test data"
}, {
    children: [{
        children: [{
            children: [],
            id: 2696,
            name: "Secondary test Data"
        }, {
            children: [],
            id: -1,
            name: "Random Text"
        }],
        id: 2575,
        name: "Another random Text"
    }],
    id: 2531,
    name: "New Data"
}]

我已经尝试过此功能

function(random){

let array3=[];
this.array.forEach(cap=>{
     let tempparent={...cap};
     let child1= tempparent.children.forEach(ch=>{
       let tempfeat={...ch};
       let tempchildren = tempfeat.children.filter(fe=>{
        if(fe.id!=random.id){
          return fe
        }
       });
     //  console.log(tempchildren)
       tempfeat.children = tempchildren;
     //  console.log(tempfeat.children)
     });
     console.log(child1)
     tempparent.children= child1;
     console.log(tempparent.children)
     nodes3.push(tempparent)
   })
   this.array= array3
   console.log(this.array);
}

我想使用id值在第三级对其进行过滤。如果ID与匹配的对象匹配,则必须将其删除。

2 个答案:

答案 0 :(得分:2)

您可以采用动态方法,将子级带出对象,检查id,如果找到,则忽略对象。

否则,请带孩子并通过递归调用获得子集,并重建一个新对象并将其推入结果集中。

这种方法不会变异原始数据,但会返回所有新对象,并可以对任意数量的级别进行工作。

function remove(array, id) {
    return array.reduce((r, { children, ...o }) => {
        if (o.id === id) return r;
        children = remove(children || [], id);
        if (children.length) o.children = children;
        r.push(o);
        return r;
    }, []);
}

var data = [{ children: [{ children: [{ children: [], id: 2694, name: "Some Random data" }, { children: [], id: 2695, name: "Another Random Data" }], id: 2574, name: "Test data", }], id: 2530, name: "Main Test data" }, { children: [{ children: [{ children: [], id: 2696, name: "Secondary test Data" }, { children: [], id: -1, name: "Random Text" }], id: 2575, name: "Another random Text" }], id: 2531, name: "New Data" }],
    result = remove(data, 2574);

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

答案 1 :(得分:1)

您可以使用递归函数。

例如,像这样

function removeById(_id,arr){
    if(arr.id === _id){
    return true;
  }else{
    arr.children.forEach(currentItem => {
        if(getById(_id,currentItem)){
            arr.children = arr.children.filter(x=>x.id !== _id);
        }
    });
  }
}

并使用此功能

removeById(2694,array[0]);
removeById(2694,array[1]);

请检查example