I orginally was going to ask a question on why it wasn’t working. But as I commented the code I realized that I could access the text array style and item was giving me the index. It took me a while to find this as the solution, however I would have much rather used item.text in the for loop. Is this [my posted answer] the valid way to loop through JSON objects in Javascript?
I orginally was going to ask a question on why it wasn’t working. But
Share
There’s no such thing as a JSON object – once you’ve parsed your JSON (which is a string) you end up with simply an object. Or an array.
Anyway, to loop through an array of objects, use a traditional
forloop. Afor..inloop may work, but is not recommended because it may loop through non-numeric properties (if somebody has been messing with the built-in array).In your specific case, if
obj.body.itemsis an array then do this:You can also, arguably, make the code a bit neater by keeping a reference directly to the array rather than accessing it via the whole
obj.body.chain every time:In your answer – which really should’ve been posted as part of the question – because you are using a
for..inloop youritemvariable is being set to each index in turn as a string, e.g., on the first iteration it will be the string"0", and strings don’t have atextproperty soitem.textdoesn’t work – although it should give youundefined, notnull. But you can do this:That is, declare a variable called
itemthat you set to reference the current array item at the beginning of each loop iteration.