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

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

问题描述

我有一个这样的家谱:

{

    "children": [{
        "name": "bob",
        "children": [{
            "name": "sam",
            "children": [{
                "name": "mike",
                "children": [{
                    "name": "elias",
                    "children": []
                }, {
                    "name": "rodriguez",
                    "children": []
                }]
            }]
        }]
    }]
}

主要的 "children" 是一个包含嵌套子数组的数组.如何从这样的数组中删除对象?假设我想删除名为sam"的对象,这应该给我留下以下内容:

The main "children" is an array containing nested child-arrays. How can I remove an object from an array like this? Lets say I want to remove the object with the name "sam", that should leave me with the following:

{
    "children": [{
        "name": "bob",
        "children": []
    }]
}

是嵌套让我绊倒了,我不知道如何开始.

Its the nesting that trips me up and i do not understand how to start.

感谢任何帮助或指导处理类似问题的教程.

Any help or directions to a tutorial that deals with similar issues are appreciated.

推荐答案

递归是处理树木的好工具.

var tree = {

    "children": [{
        "name": "bob",
        "children": [{
            "name": "sam",
            "children": [{
                "name": "mike",
                "children": [{
                    "name": "elias",
                    "children": []
                }, {
                    "name": "rodriguez",
                    "children": []
                }]
            }]
        }]
    }]
}

function removeFromTree(parent, childNameToRemove){
  parent.children = parent.children
      .filter(function(child){ return child.name !== childNameToRemove})
      .map(function(child){ return removeFromTree(child, childNameToRemove)});
  return parent;
}
tree = removeFromTree(tree, 'elias')         
console.log(tree);
document.write(JSON.stringify(tree));

本教程看起来很有趣(二叉树"和图形"部分).我认为它可以帮助实现您的要求:https://www.syncano.io/blog/data-structures-in-javascript/

This tutorial looks interesting (section "Binary Trees" and "Graphs"). I think it could help to implement your requirements: https://www.syncano.io/blog/data-structures-in-javascript/

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

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