remove object from nested array

前端 未结 4 884
感动是毒
感动是毒 2020-12-03 19:46

I have a familytree looking like this:

{

    \"children\": [{
        \"name\": \"bob\",
        \"children\": [{
            \"name\": \"sam\",
                    


        
4条回答
  •  离开以前
    2020-12-03 20:12

    This is a proposal which iterates over the objects and uses backtracking for deleting the wanted node with the given name.

    This solution keeps the original object and uses short circuit to prevent more than necessaray iterations.

    It uses recusion as well.

    function deleteFromTree(o, name) {
        function getNode(a, i) {
            if (a.name === name) {
                index = i;
                return true;
            }
            if (Array.isArray(a.children) && a.children.some(getNode)) {
                if (~index) {
                    a.children.splice(index, 1);
                    index = -1;
                }
                return true;
            }
        }
    
        var index = -1;
        [o].some(getNode);
    }
    
    var tree = { "children": [{ "name": "bob", "children": [{ "name": "sam", "children": [{ "name": "mike", "children": [{ "name": "elias", "children": [] }, { "name": "rodriguez", "children": [] }] }] }] }] };
    
    deleteFromTree(tree, 'sam');
    document.write('
    ' + JSON.stringify(tree, 0, 4) + '
    ');

提交回复
热议问题