我有一个Javascript对象像:

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

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


当前回答

对于那些想要从对象数组中删除并使用lodash的人,你可以这样做:


 const objects = [{ a: 'string', b: false, c: 'string', d: undefined }]
 const result = objects.map(({ a, b, c, d }) => _.pickBy({ a,b,c,d }, _.identity))

 // [{ a: 'string', c: 'string' }]

注意:如果你不想销毁,你不必销毁。

其他回答

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

对于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}

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

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

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

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,因为你可以完全控制你要删除的东西:

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(object, (v) => _.isUndefined(v) || _.isNull(v) || v === '');