How to remove Empty Properties from a multi depth JavaScript Object? -
i've got js object:
var test = {"code_operateur":[""],"cp_cult":["",""],"annee":["2011"],"ca_cult":[""]}
when use function:
for (i in test) { if ( test[i] == "" || test[i] === null ) { delete test[i]; } }
i get:
{"cp_cult":["",""],"annee":["2011"]}
okay not bad, i'd remove empty "cp_cult" property (which array , not string other).
note: don't want manually delete key!
try:
function isempty(thingy) { for(var k in thingy){ if(thingy[k]) { return false; } } return true; } for(i in test) { if ( test[i] == "" || test[i] === null || (typeof test[i] == "object" && isempty(test[i])) ) { delete test[i]; } }
however, depending on complexity of object, you'd need more advanced algorithms. example, if array can contain array of empty strings (or more levels) , should deleted, you'd need check well.
edit: trying make fit needs, please have at: http://jsfiddle.net/jvhne/
Comments
Post a Comment