javascript - 过滤器不适用于第三个子级别(嵌套级别)

标签 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 匹配时,必须删除匹配的对象。

最佳答案

您可以采用动态方法,将 child 从对象中取出,检查 id,如果找到,则忽略该对象。

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

这种方法不会改变原始数据,但会返回所有新对象并适用于任意数量的级别。

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; }

关于javascript - 过滤器不适用于第三个子级别(嵌套级别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57069971/

相关文章:

javascript - typescript :如何在自定义过滤器中使用 Angular $filter

javascript - 如何在javascript中创建自定义对象的公共(public)常量实例?

html - Angular 4 表单重置提交到服务器

javascript - 我如何重构我的方法?

javascript - 修补 FormBuilder 表单中的值并观察更改会导致无限循环

inheritance - 如何在 TypeScript 的派生类中重载构造函数?

javascript - 动态创建id

javascript - three.js - 将相机旋转链接到 div 内的移动设备移动

javascript - JS/Jquery 中的类型安全和强制执行

javascript - 为什么在 Selenium Webdriver (Java) 中 Gmail 密码字段无法发送带有 "sendkeys"的 key ?