Peter
Peter

Reputation: 1669

nodejs object properities - find empty element

I have an object called obj which has 20 properities. Because I'm building an XML with json xml2js builder, I want to insert only those which are NOT empty. I have the following code (variable result has sql query results from db, and sometimes it happens, that a property in object is undefined, which I want to avoid).

var obj = [] ;
 for (var i = 0; i < Object.keys(result[0]).length; i++) { 
    var value = (result[0])[Object.keys(result[0])[i]];
    obj[i] = value;
    }

What would be a fastest solution? Using try/catch would make the app slower, or?

Upvotes: 0

Views: 187

Answers (2)

Robert Moskal
Robert Moskal

Reputation: 22553

I wouldn't worry about speed, but what's readable and idiomatic. In Python there's a strong bias towards trying something and then handling the exception if it is thrown.

I don't think javascript has any such bias.

The above loop checking explicitly for null or undefined (or a add a blank string) would do fine. It's not enough to check for falsy values as you'd drop properties with a value of 0 or blank strings.

for (var i in result[0]) {
  if (result[0][i] === null || result[0][i] === undefined) {
    delete result[0][i];
  }
}

If your object descends from some other prototype, you may also want to do an additional check to make sure the property is not inherited:

obj.hasOwnProperty(i) 

Upvotes: 0

Mark Robson
Mark Robson

Reputation: 1328

A fiddle would be nice. If it is definitely an object its best to loop using var in, such as:

for (var i in result[0]) { 
     if (result[0][i]) {
         console.log(i, result[0], result[0][i]);
     }
}

Therefore you can get the key value pair, and check that the value is not falsy.

Upvotes: 1

Related Questions