amurcia
amurcia

Reputation: 791

JavaScript - Dictionary is empty

I'm using Appcelerator and I want to know if my dictionary in JS is empty.

I've tried this:

var options = {};

// Option 1
Object.keys(options).length
1

//Option 2
isEmpty(options)
false

function isEmpty(ob){
      for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
      return true;
}

//Option 3
JSON.stringify(options) === '{}'
false

Upvotes: 2

Views: 9052

Answers (1)

amurcia
amurcia

Reputation: 791

Finally I found the problem: I added one key with value 'undefined' and the JSON.stringify() function didn't show me that key.

So, this function Object.keys(options).length works perfectly.

Caution with keys with value 'undefined', check this with this function Object.keys(options) because JSON.stringify return an empty dictionary {}

var dict = {
   cat: undefined
}

Ti.API.debug("Dict: " + JSON.stringify(dict)) >  Dict: {}
Ti.API.debug("Keys: " + Object.keys(options).length) > Keys: 1
Ti.API.debug("Keys str: " + Object.keys(options)) > Keys: cat

var dict = {}

Ti.API.debug("Dict: " + JSON.stringify(dict)) >  Dict: {}
Ti.API.debug("Keys: " + Object.keys(options).length) > Keys: 0
Ti.API.debug("Keys str: " + Object.keys(options)) > Keys:

Upvotes: 3

Related Questions