I have to remove blank elements of a JSON document of unknown depth. Like this one:
{
"a": {
"a1": ""
},
"b": {
"b1": "",
"b2": {
"b21": "",
"b22": {
"b22z": "",
"b22x": ""
},
"b23": ""
},
"b3": ""
},
"c": "only non-empty field"
}
I thought that the best idea was using JSON.parse to get the object and then work on it, so I got something like this:
I found this function in this post, but it isn't working as I expeceted:
function filter(obj) {
$.each(obj, function(key, value){
if (value === "" || value === null){
delete obj[key];
} else if (Object.prototype.toString.call(value) === '[object Object]') {
filter(value);
} else if ($.isArray(value)) {
$.each(value, function (k,v) { filter(v); });
}
});
}
After calling that function with my object, I get an object with empty properties, which I don't want to show up:
How could I modify the code above to get this? I've tried everything I know and I'm going mad...
Thanks