从嵌套数组中递归删除对象 [英] Recursively remove object from nested array

查看:79
本文介绍了从嵌套数组中递归删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数组.无限数量的嵌套

i've got array like this. Unlimited number of nesting possible

const myArray = [
  {
   id: 1, 
   children: [
              { 
                id: 3,
                children: []
              }
             ]
  },
  {
   id: 2, children: []
  }
]

请帮我通过 id 删除任何对象并返回没有它的新数组.

Please, help me to remove any object by id and return new array without it.

推荐答案

recursiveRemove 函数将递归地从数组中移除元素并返回新列表.

The recursiveRemove function will recursively remove the elements from the array and return the new list.

map 函数创建数组中项目的副本,如果您不需要保留原始数组的完整性,您可以删除地图.

The map function creates copy of the items in the array, you can remove the map if you do not need to retain the original array's sanity.

function recursiveRemove ( list, id ) {
    return list.map ( item => { return {...item} }).filter ( item => {
        if ( 'children' in item ) {
            item.children = recursiveRemove ( item.children, id );
        }
        return item.id !== id;
    });
}
const test1 = recursiveRemove ( myArray, 1);
const test2 = recursiveRemove ( myArray, 2);
const test3 = recursiveRemove ( myArray, 3);

这篇关于从嵌套数组中递归删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆