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

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之类的整个对象?返回一个新数组

回答

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

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的判断逻辑

https://wintc.top/article/20
image.png

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])

以上是 如何递归删除数组中的某个对象? 的全部内容, 来源链接: utcz.com/a/32702.html

回到顶部