Reputation: 29
I am using JSON.parse(event.target.data) to load JSON data into an object.
I then access this object like this
jsonObj.product_1.title
Is it possible to dynamically set "product_1" so I can iterate through a loop for each product.
I am able to do this if each tree of the object has no name, as they can be accessed using [0], but once they have a name I seem to have to use the name.
I am trying to get to
jsonObj.[0].title
jsonObj.[1].title
jsonObj.[2].title
or
jsonObj.["product_1"].title
jsonObj.["product_2"].title
jsonObj.["product_3"].title
and so on.
Upvotes: 1
Views: 40
Reputation: 74144
You have an Associative Array
(Dictionary/Map) and you can iterator the array's items via for in
and for each in
statements.
var foodBasket:Object = {apple:"Red", orange:"Orange", corn:"Yellow"};
for in
iterate-based on the key:for (var veggie:Object in foodBasket) {
trace(veggie, foodBasket[veggie] );
}
[trace] corn Yellow
[trace] apple Red
[trace] orange Orange
for each in
iterate-based on value, not key:for each (var color:Object in foodBasket)
{
trace(color);
}
[trace] Yellow
[trace] Red
[trace] Orange
Upvotes: 0
Reputation: 1074385
Your jsonObj.["product_1"].title
is very close, just remove the .
before the [
:
jsonObj["product_1"].title
Note that the string you're using there can be the result of any expression, including a variable lookup.
In JavaScript and ActionScript, you can access an object property with dot notation and a literal property name (obj.foo
), or with brackets notation and a string property name (obj["foo"]
).*
So for instance:
var n:Number = 0;
while (jsonObj["product_" + n]) {
// Do something with `jsonObj["product_" + n].title`
++n;
}
* JavaScript also now has Symbol
property names which you also use brackets with, but that's not germane here.
Upvotes: 1