从javascript对象中删除冗余属性 [英] Remove redundant properties from javascript object
问题描述
我想从对象中删除所有空属性(包括空字符串数组)。
I'd like to remove all empty properties (including arrays of empty strings) from an object.
{ "someString" : "some text", "someObject" : { "array" : [ "", "" ] } }
例如我想从这个示例对象中删除整个分支someObject。
E.g. I'd like to remove the entire branch "someObject" from this example object.
我应该如何使用javascript进行此操作?
How should I go about doing this with javascript?
我可以编写一个递归迭代每个属性并删除空属性的函数,但在上面的示例对象中,不会删除包含空字符串的数组。
I can write a function that iterates of over each property recursively and removes empty ones, but in the example object above the array containing empty strings would not be removed.
我应该清楚,我正在寻找一个递归函数来处理比例子更复杂的对象。任意组合中的多个级别的字符串,对象和数组。
I should be clear, I am looking to write a recursive function that will handle far more complex objects than the example. Multiple levels of strings, objects and arrays in any combination.
问题是递归函数从顶部开始并向下穿过对象。因此,在一个非常长(并且是多余的)分支的末尾的空字符串将被删除,但分支本身不会。
The problem is that a recursive function starts at the top and works its way down through the object. So an empty string at the end of a very long (and otherwise redundant) branch, will be deleted but the branch itself wont.
推荐答案
到达底部后,只需如下所示遍历到根:
After reaching bottom, just traverse back to the root like so:
(function () {
Object.removeEmptiness = removeEmptiness;
function isArray(obj) {
return obj && Object.prototype.toString.call(obj) === "[object Array]" || false;
}
function isObject(obj) {
return obj && typeof obj == "object" || false;
}
function removeEmptiness(root, undef) {
var removeProps;
removeProps = function (obj, key, parent) {
var i, isFullyEmpty = true,
value;
if (isArray(obj)) {
//.length not cached on purpose
for (i = 0; i < obj.length; ++i) {
value = obj[i];
if (isObject(value)) {
removeProps(value, i, obj);
isFullyEmpty = false;
} else if (value === "" || value === undef) {
obj.splice(i--, 1);
} else {
isFullyEmpty = false;
}
}
} else {
for (i in obj) {
value = obj[i];
if (isObject(value)) {
removeProps(value, i, obj);
isFullyEmpty = false;
} else if (value === "" || value === undef) {
delete obj[i];
} else {
isFullyEmpty = false;
}
}
}
if (key !== undef && isFullyEmpty) {
delete parent[key];
removeProps(root);
}
};
removeProps(root);
return root;
}
})();
测试套房:
var obj = { "someString" : "some text", "someObject2" : {"k":"", "v": ["k"] }, "someArray3": [{}, ["","",""] ], "someObject" : { "array" : [ "", "", {"hello": ["",""] } ] } };
Object.removeEmptiness( obj );
console.log( JSON.stringify( obj ) );
//"{"someString":"some text","someObject2":{"v":["k"]}}"
这篇关于从javascript对象中删除冗余属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!