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
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
Share
Improve this question
edited Feb 10, 2016 at 13:20
Fokke Zandbergen
3,8661 gold badge13 silver badges28 bronze badges
asked Feb 8, 2016 at 13:00
amurciaamurcia
79110 silver badges27 bronze badges
9
-
What does
console.log.log(options)
show you? The first option is telling you there is one property, so what is it? Log it and see. – nnnnnn Commented Feb 8, 2016 at 13:03 - I don't know why shows one property. The console shows: options = {} – amurcia Commented Feb 8, 2016 at 13:06
-
1
But what is the key? Log
Object.keys(options)
, not the .length, so we can see what the first key is. Could that property (whatever it is) have a value that was set to undefined, or to a function? Either would be ignored by JSON. stringify. – nnnnnn Commented Feb 8, 2016 at 13:23 - 1 Thank you, you're right. I had a key with undefined value. – amurcia Commented Feb 8, 2016 at 14:44
- 1 @FokkeZandbergen done! – amurcia Commented Feb 10, 2016 at 13:28
1 Answer
Reset to default 3Finally 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: