kova February 2016

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

Answers


kova February 2016

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:

Post Status

Asked in February 2016
Viewed 3,480 times
Voted 7
Answered 1 times

Search




Leave an answer