我有一个Javascript对象像:

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

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


当前回答

如果您不想删除假值。这里有一个例子:

obj = {
  "a": null,
  "c": undefined,
  "d": "a",
  "e": false,
  "f": true
}
_.pickBy(obj, x => x === false || x)
> {
    "d": "a",
    "e": false,
    "f": true
  }

其他回答

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 +删除+未定义值+ + +对象

如果您不想删除假值。这里有一个例子:

obj = {
  "a": null,
  "c": undefined,
  "d": "a",
  "e": false,
  "f": true
}
_.pickBy(obj, x => x === false || x)
> {
    "d": "a",
    "e": false,
    "f": true
  }

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

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

对于那些想要从对象数组中删除并使用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' }]

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