js,过滤树形数据

昵称
  • 196

有以下数据

[
    {
        "id":1,
        "children":[
            {
                "id":11
            },
            {
                "id":12
            }
        ]
    },
    {
        "id":2,
        "children":[
            {
                "id":21
            },
            {
                "id":22
            }
        ]
    },
    {
        "id":3,
        "children":[
            {
                "id":21
            },
            {
                "id":32
            }
        ]
    }
]

过滤掉id=21的数据,得到:

[
    {
        "id":1,
        "children":[
            {
                "id":11
            },
            {
                "id":12
            }
        ]
    },
    {
        "id":2,
        "children":[
            {
                "id":22
            }
        ]
    },
    {
        "id":3,
        "children":null
    }
]

请问如何实现?

回复
阅读 482
2 个回答
var list = [
    {
        "id":1,
        "children":[
            {
                "id":11
            },
            {
                "id":12
            }
        ]
    },
    {
        "id":2,
        "children":[
            {
                "id":21
            },
            {
                "id":22
            }
        ]
    },
    {
        "id":3,
        "children":[
            {
                "id":21
            },
            {
                "id":32
            }
        ]
    }
];

var filterTree = (list,id)=>list.filter(item=>((flag = item.id!=id),(flag && item.children) && (item.children = filterTree(item.children, id)),flag));
filterTree(list,21);

结果

[
    {
        "id": 1,
        "children": [
            {
                "id": 11
            },
            {
                "id": 12
            }
        ]
    },
    {
        "id": 2,
        "children": [
            {
                "id": 22
            }
        ]
    },
    {
        "id": 3,
        "children": [
            {
                "id": 32
            }
        ]
    }
]
funtion (list, pickId = []) {
  return list.filter(item => {
     if (pickId.includes(item.id)) return false;
     if (item.children) {
       item.children = item.children.filter(chi => !pickId.includes(chi.id))
     }
     return true;
  })
}
你知道吗?

宣传栏