Checking length of dictionary object

Javascript

Javascript Problem Overview


I'm trying to check the length here. Tried count. Is there something I'm missing?

var dNames = {}; 
dNames = GetAllNames();

for (var i = 0, l = dName.length; i < l; i++) 
{
        alert("Name: " + dName[i].name);
}

dNames holds name/value pairs. I know that dNames has values in that object but it's still completely skipping over that and when I alert out even dName.length obviously that's not how to do this...so not sure. Looked it up on the web. Could not find anything on this.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
   if (c.hasOwnProperty(i)) count++;
}

alert(count);

Solution 3 - Javascript

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.

Solution 4 - Javascript

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}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPositiveGuyView Question on Stackoverflow
Solution 1 - JavascriptGreg HornbyView Answer on Stackoverflow
Solution 2 - JavascriptsberryView Answer on Stackoverflow
Solution 3 - Javascriptmeder omuralievView Answer on Stackoverflow
Solution 4 - JavascriptCees TimmermanView Answer on Stackoverflow