所以,这是我的函数,它从Javascript中的JSON对象中删除空属性和空属性。我需要该函数来删除空的嵌套对象,但它现在没有这样做。我已经尝试但多次失败修改此功能(我从本网站的旧帖子中得到了这个)。
有人可以帮我这个吗?
function clean_object(test, recurse) {
for (var i in test) {
if (test[i] === null || test[i] == "" ) {
delete test[i];
} else if (recurse && typeof test[i] === 'object' ) {
clean_object(test[i], recurse);
}
}
}
{ "data.openstack.public_ipv4": "falseip" }
清理后的{"data":{"openstack":{}}}
{}
提前致谢!
答案 0 :(得分:1)
作为部分方法提供的第一个开发步骤,我只想使示例以清除所有对象null
值和零长度字符串值的方式工作。
function clearEmptyValuesRecursively(obj) {
if (Array.isArray(obj)) {
obj.forEach(function (item) {
clearEmptyValuesRecursively(item);
});
} else {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if ((value === null) || (value === '')) {
delete obj[key];
} else if (typeof value !== 'string') {
clearEmptyValuesRecursively(value);
}
});
}
return obj;
}
var data = {
"data": {
"openstack": {},
"fullstack": "fullstack",
"emptyString": ""
},
"emptyData": null
};
console.log('data - before : ', JSON.stringify(data));
clearEmptyValuesRecursively(data);
console.log('data - after : ', JSON.stringify(data));
data = {
"data": {
"openstack": {}
}
};
console.log('data - before : ', JSON.stringify(data));
clearEmptyValuesRecursively(data);
console.log('data - after : ', JSON.stringify(data));
.as-console-wrapper { max-height: 100%!important; top: 0; }
......在第二步中,我采用了上述方法。这次构建递归工作函数主要用于清除空主(数据)结构,如{}
和[]
,但它也负责删除第一种方法已经显示的空值。总而言之,这也是OP所要求的......
function clearEmptyStructuresRecursively(obj) {
function isEmptyStructure(type) {
return ((Object.keys(type).length === 0) || (Array.isArray(type) && (type.length === 0)));
}
function isEmptyValue(type) {
return ((type == null) || (type === '')); // undefined or null or zero length string value.
}
if (Array.isArray(obj)) {
obj.forEach(function (item) {
clearEmptyStructuresRecursively(item);
});
} else if (obj && (typeof obj !== 'string')) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (isEmptyValue(value) || isEmptyStructure(value)) {
delete obj[key]; // ... delete ... and step into recursion ...
clearEmptyStructuresRecursively(obj);
}
clearEmptyStructuresRecursively(value);
});
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (isEmptyValue(value) || isEmptyStructure(value)) {
delete obj[key]; // ... final delete.
}
});
}
return obj;
}
var data = {
"data": {
"openstack": {}
}
};
console.log('data - before : ', JSON.stringify(data));
clearEmptyStructuresRecursively(data);
console.log('data - after : ', JSON.stringify(data));
data = {
"data": {
"openstack": {},
"fullstack": "fullstack",
"emptyString": ""
},
"emptyData": null
};
console.log('data - before : ', JSON.stringify(data));
clearEmptyStructuresRecursively(data);
console.log('data - after : ', JSON.stringify(data));
.as-console-wrapper { max-height: 100%!important; top: 0; }