开发者

How to remove Empty Properties from a multi depth JavaScript Object?

开发者 https://www.devze.com 2023-02-12 17:59 出处:网络
I\'ve got this JS Object: var test = {\"code_operateur\":[\"\"],\"cp_cult\":[\"\",\"\"],\"annee\":[\"2011\"],\"ca_cult\":[\"\"]}

I've got this JS Object:

var test = {"code_operateur":[""],"cp_cult":["",""],"annee":["2011"],"ca_cult":[""]}

When I use this function:

for (i in test) {  
   if ( test[i] == "" || test[i] === null ) {  
       delete test[i];  
    }  
}

I get:

{"cp_cult":["",""],"annee":["2011"]}

Okay not bad, but I'd like to rem开发者_Python百科ove the empty "cp_cult" property (which is an array and not a string like the other).

Note: I don't want to manually delete the key!


It looks like you're asking 2 questions here.

  1. How do I remove a property of an object; and
  2. How can I tell if an object is actually an array.

You can delete a property of an object using the delete operator.

delete test.cp_cult;

In JavaScript arrays are objects, which means that typeof([]) unhelpfully returns object. Typically people work around this by using a function in a framework (dojo.isArray or something similar) or rolling their own method that determines if an object is an array.

There is no 100% guaranteed way to determine if an object is actually an array. Most people just check to see if it has some of the methods/properties of an array length, push, pop, shift, unshift, etc.


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 the complexity of the object, you'd need more advanced algorithms. For example, if the array can contain another array of empty strings (or even more levels) and it should be deleted, you'd need to check for that as well.

EDIT: Trying to make something to fit your needs, please have a look at: http://jsfiddle.net/jVHNe/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号