我有一个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属性应该保留。
当前回答
我喜欢用_。pickBy,因为你可以完全控制你要删除的东西:
var person = {"name":"bill","age":21,"sex":undefined,"height":null};
var cleanPerson = _.pickBy(person, function(value, key) {
return !(value === undefined || value === null);
});
来源:https://www.codegrepper.com/?search_term=lodash +删除+未定义值+ + +对象
其他回答
如果您不想删除假值。这里有一个例子:
obj = {
"a": null,
"c": undefined,
"d": "a",
"e": false,
"f": true
}
_.pickBy(obj, x => x === false || x)
> {
"d": "a",
"e": false,
"f": true
}
考虑到undefined == null,我们可以这样写:
let collection = {
a: undefined,
b: 2,
c: 4,
d: null,
}
console.log(_.omit(collection, it => it == null))
// -> { b: 2, c: 4 }
JSBin例子
用于深嵌套的对象和数组。并从字符串和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"
}
默认情况下,pickBy使用identity:
_.pickBy({ a: null, b: 1, c: undefined, d: false });
我也会使用下划线并处理空字符串:
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.