frenetix
frenetix

Reputation: 1209

best way to append an item to a list within a JSON object?

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!!

Upvotes: 1

Views: 378

Answers (4)

ntangjee
ntangjee

Reputation: 301

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);

Upvotes: 2

Jason Strimpel
Jason Strimpel

Reputation: 15506

Use the following the find the length of dynamicList object:

Object.keys(obj.dynamicList).length

Upvotes: 1

miki
miki

Reputation: 695

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.

Upvotes: 0

cdhowie
cdhowie

Reputation: 169328

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.

Upvotes: 1

Related Questions