Possible Duplicate:
I have a nested data structure /how can I access a specific value?
How can I get the name and value of each object in Javascript only?
Possible Duplicate:
I have a nested data structure /how can I access a specific value?
How can I get the name and value of each object in Javascript only?
Ok, here is the JS code:
FIDDLE HERE
There are two ways to access properties of objects:
Or, if you need to dynamically do it:
If you don't already have it as an object, you'll need to convert it.
For a more complex example, let's assume you have an array of objects that represent users:
To access the age property of the second user, you would use
users[1].age
. To access the second "favoriteFood" of the first user, you'd useusers[0].favoriteFoods[2]
.Another example:
obj[2].key[3]["some key"]
That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name
some key
.As Amadan noted, it might be worth also discussing how to loop over different structures.
To loop over an array, you can use a simple for loop:
To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain
for (x in obj) { }
loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)(Note that I've assumed whatever JS implementation you're using has
console.log
. If not, you could usealert
or some kind of DOM manipulation instead.)my solution
Approved code
result
*You should use distinguish accessorizes when using [] method or dot notation
Try the JSON Parser by Douglas Crockford at github. You can then simply create a JSON object out of your String variable as shown below: