我有一个Javascript对象像:

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

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


当前回答

根据lodash文档:

_.compact(_.map(array, fn))

你也可以过滤掉所有的空值

其他回答

如果你想移除所有假值,那么最紧凑的方法是:

对于Lodash 4。X及以后:

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

对于遗留的Lodash 3.x:

_.pick(obj, _.identity);

_.pick({ a: null, b: 1, c: undefined }, _.identity);
>> Object {b: 1}

你也可以使用Object。使用Array.prototype.filter。

const omitNullish = (object) => 
   Object.fromEntries(
       Object.entries(object).filter(([, value]) => value != null)
   )

omitNullish({ a: null, b: 1, c: undefined, d: false, e: 0 }) // { b: 1, d: false, e: 0}

如果你想使用lodash,他们从v5中删除了省略,所以另一种选择是使用fp/pickBy以及isNil和negate。

import pickBy from 'lodash/fp/pickBy'
import isNil from 'lodash/isNil';
import negate from 'lodash/negate';


const omitNullish = pickBy(negate(isNil))

omitNullish({ a: null, b: 1, c: undefined, d: false, e: 0 }) // { b: 1, d: false, e: 0}

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

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

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

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

JSBin例子

正确答案是:

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

结果是:

{b: 1, d: false}

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

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

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