我有一个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}
其他回答
从对象中删除未定义、空字符串和空字符串
_.omitBy(object, (v) => _.isUndefined(v) || _.isNull(v) || v === '');
我也会使用下划线并处理空字符串:
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.
因为你们中的一些人可能已经想到了这个问题,想要明确地删除undefined,你可以使用:
Lodash方法的组合 _。_.isUndefined omitBy(对象) rundef包,它只删除未定义的属性 rundef(对象)
如果需要递归地删除未定义的属性,rundef包还有一个递归选项。
rundef(object, false, 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 }
考虑到undefined == null,我们可以这样写:
let collection = {
a: undefined,
b: 2,
c: 4,
d: null,
}
console.log(_.omit(collection, it => it == null))
// -> { b: 2, c: 4 }
JSBin例子