如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
除了删除属性,还可以使用非空键创建一个新对象。
const removeEmpty = (obj) => {
return Object.keys(obj).filter(key => obj[key]).reduce(
(newObj, key) => {
newObj[key] = obj[key]
return newObj
}, {}
)
}
其他回答
来piggypack本的回答如何解决这个问题使用lodash的_。pickBy,你也可以在姐妹库中解决这个问题:Underscore.js的_.pick。
var obj = {name: 'John', age: null};
var compacted = _.pick(obj, function(value) {
return value !== null && value !== undefined;
});
参见:JSFiddle示例
如果有人需要使用lodash从对象中删除未定义的值,然后这里是我使用的代码。修改它以删除所有空值(null/undefined)非常简单。
function omitUndefinedDeep(obj) {
return _.reduce(obj, function(result, value, key) {
if (_.isObject(value)) {
result[key] = omitUndefinedDeep(value);
}
else if (!_.isUndefined(value)) {
result[key] = value;
}
return result;
}, {});
}
你也可以用…使用forEach扩展语法,如下所示:
设 obj = { a: 1, b: “b”, c: undefined, d: null }; let cleanObj = {}; Object.keys(obj).forEach(val => { const newVal = obj[val]; cleanObj = newVal ?{ ...cleanObj, [val]: newVal } : cleanObj; }); console.info(清洁对象);
清除空数组、空对象、空字符串、未定义、NaN和空值。
function objCleanUp(obj:any) {
for (var attrKey in obj) {
var attrValue = obj[attrKey];
if (attrValue === null || attrValue === undefined || attrValue === "" || attrValue !== attrValue) {
delete obj[attrKey];
} else if (Object.prototype.toString.call(attrValue) === "[object Object]") {
objCleanUp(attrValue);
if(Object.keys(attrValue).length===0)delete obj[attrKey];
} else if (Array.isArray(attrValue)) {
attrValue.forEach(function (v,index) {
objCleanUp(v);
if(Object.keys(v).length===0)attrValue.splice(index,1);
});
if(attrValue.length===0)delete obj[attrKey];
}
}
}
objCleanUp(myObject)
(attrValue !== attrValue)检查NaN。在这里学的
使用ramda#pickBy你将删除所有null, undefined和false值:
const obj = {a:1, b: undefined, c: null, d: 1}
R.pickBy(R.identity, obj)
正如@manroe指出的,要保留假值,请使用isNil():
const obj = {a:1, b: undefined, c: null, d: 1, e: false}
R.pickBy(v => !R.isNil(v), obj)