我有一个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}

我喜欢用_。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 +删除+未定义值+ + +对象

你也可以使用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}

正确答案是:

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

结果是:

{b: 1, d: false}

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

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

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

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

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.