Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - remove object from nested array

I have a familytree looking like this:

{

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Recursion is a good tool to work with trees.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...