我有一个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属性应该保留。
当前回答
用于深嵌套的对象和数组。并从字符串和NaN中排除空值
function isBlank(value) {
return _.isEmpty(value) && !_.isNumber(value) || _.isNaN(value);
}
var removeObjectsWithNull = (obj) => {
return _(obj).pickBy(_.isObject)
.mapValues(removeObjectsWithNull)
.assign(_.omitBy(obj, _.isObject))
.assign(_.omitBy(obj, _.isArray))
.omitBy(_.isNil).omitBy(isBlank)
.value();
}
var obj = {
teste: undefined,
nullV: null,
x: 10,
name: 'Maria Sophia Moura',
a: null,
b: '',
c: {
a: [{
n: 'Gleidson',
i: 248
}, {
t: 'Marta'
}],
g: 'Teste',
eager: {
p: 'Palavra'
}
}
}
removeObjectsWithNull(obj)
结果:
{
"c": {
"a": [
{
"n": "Gleidson",
"i": 248
},
{
"t": "Marta"
}
],
"g": "Teste",
"eager": {
"p": "Palavra"
}
},
"x": 10,
"name": "Maria Sophia Moura"
}
其他回答
根据lodash文档:
_.compact(_.map(array, fn))
你也可以过滤掉所有的空值
最短路径(lodash v4):
_.pickBy(my_object)
考虑到undefined == null,我们可以这样写:
let collection = {
a: undefined,
b: 2,
c: 4,
d: null,
}
console.log(_.omit(collection, it => it == null))
// -> { b: 2, c: 4 }
JSBin例子
你也可以使用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}
如果你想移除所有假值,那么最紧凑的方法是:
对于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}