Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a json array which looks something like this:

  {
    "id": 1,
    "children": [
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    }]
}

I would like to have a function which removes the elements which has the "children" empty. How can I do it? I am not asking for the answer, only suggestions

See Question&Answers more detail:os

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

1 Answer

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...