我有一个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属性应该保留。
当前回答
你也可以使用Object。使用Array.prototype.filter。
const omitNullish = (object) =>
Object.fromEntries(
Object.entries(object).filter(([, value]) => value != null)
)
omitNullish({ a: null, b: 1, c: undefined, d: false, e: 0 }) // { b: 1, d: false, e: 0}
如果你想使用lodash,他们从v5中删除了省略,所以另一种选择是使用fp/pickBy以及isNil和negate。
import pickBy from 'lodash/fp/pickBy'
import isNil from 'lodash/isNil';
import negate from 'lodash/negate';
const omitNullish = pickBy(negate(isNil))
omitNullish({ a: null, b: 1, c: undefined, d: false, e: 0 }) // { b: 1, d: false, e: 0}
其他回答
从对象中删除未定义、空字符串和空字符串
_.omitBy(object, (v) => _.isUndefined(v) || _.isNull(v) || v === '');
考虑到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 > 4
const removeObjectsWithNull = (obj) => {
return _(obj)
.pickBy(_.isObject) // get only objects
.mapValues(removeObjectsWithNull) // call only for values as objects
.assign(_.omitBy(obj, _.isObject)) // save back result that is not object
.omitBy(_.isNil) // remove null and undefined from object
.value(); // get value
};
根据lodash文档:
_.compact(_.map(array, fn))
你也可以过滤掉所有的空值
如果你想移除所有假值,那么最紧凑的方法是:
对于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}