怎么根据id数组从数据数组里删除相关数据?

选中删除数据的时候,选中的数据id会组成一个数组,然后从所有的数据数组的第一层里删掉这个数据,同时如果数据有children,children里有这条数据,那就从第一层里删除这条数据

data = [{

    flg: "0",
    id: "1001",
    name: "一级1",
    children: [{
      flg: "0",
      id: "100101",
      name: "二级1"
    }, {
      flg: "0",
      id: "100102",
      name: "二级2"
    }, {
      flg: "0",
      id: "100103",
      name: "二级3"
    }]
  }, {
    flg: "0",
    id: "100101",
    name: "二级1"
  }, {
    flg: "0",
    id: "100102",
    name: "二级2"
  }, {
    flg: "0",
    id: "100103",
    name: "二级3"
  }]

cacel = ['100103']

要得到的数据是
[{

    flg: "0",
    id: "100101",
    name: "二级1"
  }, {
    flg: "0",
    id: "100102",
    name: "二级2"
  }]
阅读 3.1k
1 个回答

主要用到了递归

可执行例子:
https://codepen.io/LiangWei88...

代码:

let data = [
    {
        flg: "0",
        id: "1001",
        name: "一级1",
        children: [{
            flg: "0",
            id: "100101",
            name: "二级1"
        }, {
            flg: "0",
            id: "100102",
            name: "二级2"
        }, {
            flg: "0",
            id: "100103",
            name: "二级3"
        }]
    }, 
    {
        flg: "0",
        id: "100101",
        name: "二级1"
    }, 
    {
        flg: "0",
        id: "100102",
        name: "二级2"
    }, 
    {
        flg: "0",
        id: "100103",
        name: "二级3"
    }
];

let idToDelete = "100103";

let result = filterData(data);
console.log(result);

function filterData(data) {
    return data.reduce((acc, current) => {
        if (current.id == idToDelete) {
            return acc;
        } else {
            if (current.children) {
                let res = filterData(current.children);
                if (res.length < current.children.length) {
                    return acc;
                }
            }
            acc.push(current);
            return acc;
        }
    }, []);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题