How to remove undefined and null values from an object using lodash?

前端 未结 23 2224
既然无缘
既然无缘 2020-11-29 18:06

I have a Javascript object like:

var my_object = { a:undefined, b:2, c:4, d:undefined };

How to remove all the undefined properties? False

相关标签:
23条回答
  • Since some of you might have arrived at the question looking to specifically removing only undefined, you can use:

    • a combination of Lodash methods

      _.omitBy(object, _.isUndefined)
      
    • the rundef package, which removes only undefined properties

      rundef(object)
      

    If you need to recursively remove undefined properties, the rundef package also has a recursive option.

    rundef(object, false, true);
    

    See the documentation for more details.

    0 讨论(0)
  • 2020-11-29 18:31

    I would use underscore and take care of empty strings too:

    var my_object = { a:undefined, b:2, c:4, d:undefined, k: null, p: false, s: '', z: 0 };
    
    var result =_.omit(my_object, function(value) {
      return _.isUndefined(value) || _.isNull(value) || value === '';
    });
    
    console.log(result); //Object {b: 2, c: 4, p: false, z: 0}

    jsbin.

    0 讨论(0)
  • 2020-11-29 18:32

    If you don't want to remove false values. Here is an example:

    obj = {
      "a": null,
      "c": undefined,
      "d": "a",
      "e": false,
      "f": true
    }
    _.pickBy(obj, x => x === false || x)
    > {
        "d": "a",
        "e": false,
        "f": true
      }
    
    0 讨论(0)
  • 2020-11-29 18:34

    if you are using lodash, you can use _.compact(array) to remove all falsely values from an array.

    _.compact([0, 1, false, 2, '', 3]);
    // => [1, 2, 3]
    

    https://lodash.com/docs/4.17.4#compact

    0 讨论(0)
  • 2020-11-29 18:34

    pickBy uses identity by default:

    _.pickBy({ a: null, b: 1, c: undefined, d: false });
    
    0 讨论(0)
提交回复
热议问题