tags:

views:

32

answers:

2

For example lets say I have a JSON object that contains states and cities. like so

var obj = { states : [ {'state1' : {cities : ['city', 'another']} } ] }

Now lets say our script adds a state by doing obj.states.push(stateVar)

How can we add cities to this newly created state? I have tried things like obj.states[1].push(cityVar) or obj.states[1].cities.push(); but that gives a this is not a function error.

+1  A: 

It smells as though your structure is a bit off. You probably want something like this:

var obj = { states : {'state1' : {cities : ['city', 'another']} } }
obj.states[newState] = {cities : ['even', 'more', 'cities']}
obj.states[newState].cities.push('again')
Ignacio Vazquez-Abrams
+1  A: 

You can either change states as an object as this answer suggested or you can change it to this form -

 var obj = {states : [
     { name: 'state1', cities : [ 'city1', 'city2'] },
     { name: 'state2', cities : [ 'city1', 'city2'] }
 ]}

Think about it, as per your structure, if you only have a state object, you can not access it's cities unless you know the state name! (It is possible, but it gets ugly)

It depends on your use case whether you want an Object or an Array. Object is good for fast lookups by keys whereas arrays are good for enumeration and they maintain the order. (Objects maintain the order in most implementations too, but it is not in spec and hence not guaranteed.)

Chetan Sastry