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

前端 未结 23 2349
既然无缘
既然无缘 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条回答
  •  自闭症患者
    2020-11-29 18:29

    For deep nested object and arrays. and exclude empty values from string and NaN

    function isBlank(value) {
      return _.isEmpty(value) && !_.isNumber(value) || _.isNaN(value);
    }
    var removeObjectsWithNull = (obj) => {
      return _(obj).pickBy(_.isObject)
        .mapValues(removeObjectsWithNull)
        .assign(_.omitBy(obj, _.isObject))
        .assign(_.omitBy(obj, _.isArray))
        .omitBy(_.isNil).omitBy(isBlank)
        .value();
    }
    var obj = {
      teste: undefined,
      nullV: null,
      x: 10,
      name: 'Maria Sophia Moura',
      a: null,
      b: '',
      c: {
        a: [{
          n: 'Gleidson',
          i: 248
        }, {
          t: 'Marta'
        }],
        g: 'Teste',
        eager: {
          p: 'Palavra'
        }
      }
    }
    removeObjectsWithNull(obj)
    

    result:

    {
       "c": {
          "a": [
             {
                "n": "Gleidson",
                "i": 248
             },
             {
                "t": "Marta"
             }
          ],
          "g": "Teste",
          "eager": {
             "p": "Palavra"
          }
       },
       "x": 10,
       "name": "Maria Sophia Moura"
    }
    

提交回复
热议问题