Recursively remove null values from JavaScript object

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

    Please use this npm package

    npm i --save nnjson
    var nnjson = require('nnjson');
    user = {
      a: null,
      b: 'hello',
      c: {
        c1: 'world',
        c2: null
      }
    }
    var newUser = nnjson.removeNull(user);
    console.log (newUser)
    

    result

    {
      b: 'hello',
      c: {
        c1: 'world'
      }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题