我有一个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}
其他回答
考虑到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 }
如果你想移除所有假值,那么最紧凑的方法是:
对于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); }));
我能够在深层对象中做到这一点,其中包括数组,只有一个lodash函数,transform。
注意,双重不相等(!= null)是有意的,因为它也将匹配undefined, typeof 'object'检查也是如此,因为它将匹配object和array。
这只用于不包含类的普通数据对象。
const cloneDeepSanitized = (obj) =>
Array.isArray(obj)
? obj.filter((entry) => entry != null).map(cloneDeepSanitized)
: transform(
obj,
(result, val, key) => {
if (val != null) {
result[key] =
typeof val === 'object' ? cloneDeepSanitized(val) : val;
}
},
{},
);