Recursively remove null values from JavaScript object

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

    Fixing your book array is easy enough - you just have to filter out the nulls. The most straightforward way would probably be building a new array and reassigning it:

    var temp = [];
    var i;
    for (i = 0; i < obj.store.book.length; ++i) {
        if (obj.store.book[i] != null) {
            temp.push(obj.store.book[i]);
        }
    }
    obj.store.book = temp;
    

    I'm sure there are plenty of other ways, like using jQuery, or the filter function (which I believe is not available in older browsers). You could also loop through the array and splice out the nulls. I just find this way the easiest to read.

提交回复
热议问题