1

I'm working on JavaScript and I have this JSON object:

var obj ={"name" : "objName",
    "dynamicList" :[]};

and then I add some items to my list like this:

obj.dynamicList["someStringID"] = {"watever"};

It's important that I use a string as indexer for each item on my list (i didn't know this could be done until recently).

My only problem now is that whenever I ask for obj.dynamicList.lenght I get 0, unles I manually set the proper number... I was wondering if there's a better way to add items to my list?

Thanks!!

cdhowie
  • 133,716
  • 21
  • 261
  • 264
frenetix
  • 1,150
  • 1
  • 10
  • 17

4 Answers4

2

In Javascript, string index is not really an index. It's actually an attribute of the array object. You could set and get the value with the string index, but it's actually an empty array with some attributes. Not only .length, but also .sort(), .splice(), and other array function would not work. If there is a need to use array functions, I would use number as an index to make it a real item in the array.

If you have to use the string as an index, you couldn't rely on .length function. If there is no need to support IE prior to version 9, the Object.keys as suggested by @strimp099 should work. or you may have to create function to count the number of attributes for example:

function len(obj) {
    var attrCount = 0;
    for(var k in obj) {
        attrCount++;
    }
    return attrCount;
}

and then call

len(obj.dynamicList);
ntangjee
  • 301
  • 1
  • 2
  • Thanks for the answer ntangjee. Even though this was the most informative answer, I'll implement strimp099's suggestion, since I don't care about IE compatibility for this project. So I'm giving him this point. I just wanted to thank you and as soon as I get my 15 points I'll get back here and vote up your answer :) – frenetix Sep 04 '11 at 19:15
1

To do this "the right way," you will have to make obj.dynamicList an object instead of an array; use {} instead of [] to set the initial value.

cdhowie
  • 133,716
  • 21
  • 261
  • 264
1

Use the following the find the length of dynamicList object:

Object.keys(obj.dynamicList).length
Jason Strimpel
  • 11,832
  • 19
  • 65
  • 95
0

How to efficiently count the number of keys/properties of an object in JavaScript?

dynamiclist is an object, the length is not the length property you expect from an array.

Community
  • 1
  • 1
miki
  • 695
  • 3
  • 8