Recursively remove null values from JavaScript object

前端 未结 8 907
挽巷
挽巷 2020-12-28 16:07

I have a JSON obj, after some operations (like delete some pieces), I print it and everything looks good except that I have some null values. How do I remove th

8条回答
  •  庸人自扰
    2020-12-28 16:39

    // Iterate the array from back to front, removing null entries
    for (var i=obj.store.book.length;i--;){
      if (obj.store.book[i]===null) obj.store.book.splice(i,1);
    }
    

    If you want to remove all null values recursively from both objects and arrays:

    // Compact arrays with null entries; delete keys from objects with null value
    function removeNulls(obj){
      var isArray = obj instanceof Array;
      for (var k in obj){
        if (obj[k]===null) isArray ? obj.splice(k,1) : delete obj[k];
        else if (typeof obj[k]=="object") removeNulls(obj[k]);
      }
    }
    

    Seen in action:

    var o = {
      "store": {
        "book": [
           null,
           {
             "category": "fiction",
             "author": "Evelyn Waugh",
             "title": "Sword of Honour",
             "price": 12.99
           },
           null,
           {
              "category": "fiction",
              "author": "J. R. R. Tolkien",
              "title": "The Lord of the Rings",
              "isbn": "0-395-19395-8",
              "price": 22.99
           }
        ],
        "bicycle": {
           "color": "red",
           "bad": null,
           "price": 19.95
        }
      }
    }
    
    removeNulls(o);
    
    console.log(JSON.stringify(o,null,2));
    // {
    //   "store": {
    //     "book": [
    //       {
    //         "category": "fiction",
    //         "author": "Evelyn Waugh",
    //         "title": "Sword of Honour",
    //         "price": 12.99
    //       },
    //       {
    //         "category": "fiction",
    //         "author": "J. R. R. Tolkien",
    //         "title": "The Lord of the Rings",
    //         "isbn": "0-395-19395-8",
    //         "price": 22.99
    //       }
    //     ],
    //     "bicycle": {
    //       "color": "red",
    //       "price": 19.95
    //     }
    //   }
    // }
    

提交回复
热议问题