Checking length of dictionary object [duplicate]
What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length
var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
if (c.hasOwnProperty(i)) count++;
}
alert(count);
This question is confusing. A regular object, {}
doesn't have a length
property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in
statement on the object, since length
is not set, and increment a counter.
I'm confused as to why you need the length
. Are you manually setting 0
on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';
. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length
is already set.
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}