Skip to content Skip to sidebar Skip to footer

How To Remove Empty Properties From A Multi Depth Javascript Object?

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] ==

Solution 1:

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.

Solution 2:

Try:

function isEmpty(thingy) {
 for(var k in thingy){
  if(thingy[k]) {
   returnfalse;
  }
 }
 returntrue;
}

for(i intest) {
 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/

Post a Comment for "How To Remove Empty Properties From A Multi Depth Javascript Object?"