js,过滤树形数据

有以下数据

[
    {
        "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
    }
]

请问如何实现?

阅读 2.8k
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;
  })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题