开发者

Add to JSON without knowing its structure

开发者 https://www.devze.com 2023-01-13 13:50 出处:网络
For example lets say I have a JSON object that conta开发者_JS百科ins states and cities. like so var obj = {

For example lets say I have a JSON object that conta开发者_JS百科ins 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消