Remove element from JSON Object

后端 未结 2 522
甜味超标
甜味超标 2020-12-05 04:11

I have a json array which looks something like this:

  {
    \"id\": 1,
    \"children\": [
    {
        \"id\": 2,
        \"children\": {
            \"id         


        
相关标签:
2条回答
  • 2020-12-05 04:44

    JSfiddle

    function deleteEmpty(obj){
            for(var k in obj)
             if(k == "children"){
                 if(obj[k]){
                         deleteEmpty(obj[k]);
                 }else{
                       delete obj.children;
                  } 
             }
        }
    
    for(var i=0; i< a.children.length; i++){
     deleteEmpty(a.children[i])
    }
    
    0 讨论(0)
  • 2020-12-05 04:56

    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:

    • https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
    • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in
    • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete
    0 讨论(0)
提交回复
热议问题