Recursively remove null values from JavaScript object

前端 未结 8 920
挽巷
挽巷 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:40

    The following is a modification to the answer by @Phrogz. If book[3] was also null, the answer given would not remove the last null because the array's length would be less than k in last loop's iteration.

    The following would work by performing a second call to the array:

    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]);
        if (isArray && obj.length == k) removeNulls(obj);
      }
      return obj;
    }
    

提交回复
热议问题