我有一个Javascript对象像:
var my_object = { a:undefined, b:2, c:4, d:undefined };
如何删除所有未定义的属性?False属性应该保留。
我有一个Javascript对象像:
var my_object = { a:undefined, b:2, c:4, d:undefined };
如何删除所有未定义的属性?False属性应该保留。
当前回答
如果你想移除所有假值,那么最紧凑的方法是:
对于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}
其他回答
只是:
_.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); }));
因为你们中的一些人可能已经想到了这个问题,想要明确地删除undefined,你可以使用:
Lodash方法的组合 _。_.isUndefined omitBy(对象) rundef包,它只删除未定义的属性 rundef(对象)
如果需要递归地删除未定义的属性,rundef包还有一个递归选项。
rundef(object, false, true);
有关详细信息,请参阅文档。
以下是我采用的lodash方法:
_(my_object)
.pairs()
.reject(function(item) {
return _.isUndefined(item[1]) ||
_.isNull(item[1]);
})
.zipObject()
.value()
函数的作用是:将输入对象转换为键/值数组数组。这样做是为了更容易使用reject()来消除未定义值和空值。之后,剩下的是没有被拒绝的对,这些是zipObject()的输入,它为您重建对象。
考虑到undefined == null,我们可以这样写:
let collection = {
a: undefined,
b: 2,
c: 4,
d: null,
}
console.log(_.omit(collection, it => it == null))
// -> { b: 2, c: 4 }
JSBin例子
如果使用lodash,可以使用_.compact(array)从数组中删除所有错误值。
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
https://lodash.com/docs/4.17.4#compact