我有一个Javascript对象像:

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

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


当前回答

考虑到undefined == null,我们可以这样写:

let collection = {
  a: undefined,
  b: 2,
  c: 4,
  d: null,
}

console.log(_.omit(collection, it => it == null))
// -> { b: 2, c: 4 }

JSBin例子

其他回答

只是:

_.omit(my_object, _.isUndefined)

上面没有考虑到空值,因为它们在原始示例中没有出现,只在主题中提到过,但我保留了它,因为它很优雅,可能有它的用途。

下面是完整的示例,虽然不那么简洁,但更完整。

var obj = { a: undefined, b: 2, c: 4, d: undefined, e: null, f: false, g: '', h: 0 };
console.log(_.omit(obj, function(v) { return _.isUndefined(v) || _.isNull(v); }));

我能够在深层对象中做到这一点,其中包括数组,只有一个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;
          }
        },
        {},
      );

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

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.

我喜欢用_。pickBy,因为你可以完全控制你要删除的东西:

var person = {"name":"bill","age":21,"sex":undefined,"height":null};

var cleanPerson = _.pickBy(person, function(value, key) {
  return !(value === undefined || value === null);
});

来源:https://www.codegrepper.com/?search_term=lodash +删除+未定义值+ + +对象

正确答案是:

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

结果是:

{b: 1, d: false}

其他人给出的另一种说法:

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

也将删除这里不需要的假值。