My task is to remove empty elements from a JSON document that has an unknown depth, similar to the one below:
{
"a": {
"a1": ""
},
"b": {
"b1": "",
"b2": {
"b21": "",
"b22": {
"b22z": "",
"b22x": ""
},
"b23": ""
},
"b3": ""
},
"c": "only non-empty field"
}
I decided to use JSON.parse to extract the object and then manipulate it. However, after attempting the function found in this post, I encountered issues:
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); });
}
});
}
Running this function on my object resulted in empty properties remaining, which was not the desired outcome:
https://i.sstatic.net/RWHA2.png
I have tried several modifications but haven't been successful. Any suggestions would be greatly appreciated. Thank you.