我有一个Javascript对象像:

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

如何删除所有未定义的属性?False属性应该保留。


当前回答

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

var newObject = _.reject(my_collection, function(val){ return _.isUndefined(val) })

//--> newCollection = { b: 2, c: 4 }

其他回答

用于深嵌套的对象和数组。并从字符串和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)

结果:

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

我也会使用下划线并处理空字符串:

Var my_object = {a:undefined, b:2, c:4, d:undefined, k: null, p: false, s: ", z: 0}; Var结果=_。省略(my_object, function(value) { return _.isUndefined(value) || _.isNull(value) || value === "; }); console.log(结果);//对象{b: 2, c: 4, p: false, z: 0}

JSBIN.

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

var newObject = _.reject(my_collection, function(val){ return _.isUndefined(val) })

//--> newCollection = { b: 2, c: 4 }

默认情况下,pickBy使用identity:

_.pickBy({ a: null, b: 1, c: undefined, d: false });

我能够在深层对象中做到这一点,其中包括数组,只有一个lodash函数,transform。

注意,双重不相等(!= null)是有意的,因为它也将匹配undefined, typeof 'object'检查也是如此,因为它将匹配object和array。

这只用于不包含类的普通数据对象。

const cloneDeepSanitized = (obj) =>
  Array.isArray(obj)
    ? obj.filter((entry) => entry != null).map(cloneDeepSanitized)
    : transform(
        obj,
        (result, val, key) => {
          if (val != null) {
            result[key] =
              typeof val === 'object' ? cloneDeepSanitized(val) : val;
          }
        },
        {},
      );