如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
JSON。Stringify删除未定义的键。
removeUndefined = function(json){
return JSON.parse(JSON.stringify(json))
}
其他回答
你可以循环遍历对象:
Var检验= { test1:空, test2:“somestring”, test3: 3, } 函数clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { 删除obj [propName]; } } 返回obj } console.log(测试); console.log(清洁(测试));
如果你担心这个属性删除不会运行到对象的proptype链,你还可以:
function clean(obj) {
var propNames = Object.getOwnPropertyNames(obj);
for (var i = 0; i < propNames.length; i++) {
var propName = propNames[i];
if (obj[propName] === null || obj[propName] === undefined) {
delete obj[propName];
}
}
}
关于null和undefined的一些注意事项:
test.test1 === null; // true
test.test1 == null; // true
test.notaprop === null; // false
test.notaprop == null; // true
test.notaprop === undefined; // true
test.notaprop == undefined; // true
您可能正在寻找delete关键字。
var obj = { };
obj.theProperty = 1;
delete obj.theProperty;
清除空数组、空对象、空字符串、未定义、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。在这里学的
我们可以使用JSON。stringify和JSON。解析以从对象中删除空白属性。
jsObject = JSON.parse(JSON.stringify(jsObject), (key, value) => {
if (value == null || value == '' || value == [] || value == {})
return undefined;
return value;
});
如果您更喜欢纯/函数方法
const stripUndef = obj =>
Object.keys(obj)
.reduce((p, c) => ({ ...p, ...(x[c] === undefined ? { } : { [c]: x[c] })}), {});