如何递归删除数组中的某个对象?

data: [
      {
        id: 1,
        name: 'mock',
        type: 1,
        subs: [
          {
            id: 4,
            name: 'agency.sol',
            type: 2,
            subs: {
              id: 10,
              name: 'account.sol',
              type: 2,
              subs: null,
            },
          },
          {
            id: 5,
            name: 'blockchain.sol',
            type: 2,
            subs: null,
          },
        ],
      },
      {
        id: 2,
        name: 'public',
        type: 1,
        subs: [
          {
            id: 6,
            name: 'vote.sol',
            type: 2,
            subs: null,
          },
          {
            id: 7,
            name: 'user.sol',
            type: 2,
            subs: null,
          },
        ],
      },
    ]

比如这样一个嵌套的有子集的数组,如何快速删除比如id为4,或者id为2之类的整个对象?返回一个新数组

阅读 5k
4 个回答
function filter(condition=()=>false, key) {
  return function filtrate(data) {
    return data.reduce((res, item) => {
      if( !condition(item) ) {
        const children = item[key];
           res.push({
          ...item,
          [key]: Array.isArray(children) ? filtrate(children) : children,
        }); 
      }
      return res;
    }, []);
  }
}


var data = [
      {
        id: 1,
        name: 'mock',
        type: 1,
        subs: [
          {
            id: 4,
            name: 'agency.sol',
            type: 2,
            subs: {
              id: 10,
              name: 'account.sol',
              type: 2,
              subs: null,
            },
          },
          {
            id: 5,
            name: 'blockchain.sol',
            type: 2,
            subs: null,
          },
        ],
      },
      {
        id: 2,
        name: 'public',
        type: 1,
        subs: [
          {
            id: 6,
            name: 'vote.sol',
            type: 2,
            subs: null,
          },
          {
            id: 7,
            name: 'user.sol',
            type: 2,
            subs: null,
          },
        ],
      },
    ];

var filterIdEqual2 = filter(item => item.id == 2, 'subs')
var filterIdEqual7 = filter(item => item.id == 7, 'subs')

console.log(filterIdEqual2(data))
console.log('----------')
console.log(filterIdEqual7(data))

ps:这里的filter传入的回调判断与原生数组的filter的意思相反,更符合直觉,当然也可以改成同原生filter的判断逻辑

递归深拷贝中将不需要的值过滤掉

function filterTree (tree = [], map = [], arr = []) {
    if (!tree.length) return []
    for (let item of tree) {
        if (map.includes(item.id)) continue
        let node = undefined
        if (Array.isArray(item.subs)) {
            node = {...item, subs: []}
        } else {
            node = {...item}
        }
        arr.push(node)
        if (item.subs && item.subs.length) filterTree(item.subs, map, node.subs)
    }
    return arr
}

const result = filterTree(data, [6, 7])
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题