I'm trying to understand how to iterate over an object that resembles the following:
var json = {"tsn": {
"events": [
{
"title": "Lorem ipsum",
"description": "Dolor sit"
},
{
"title": "Duis aute irure",
"description": "eu fugiat nulla pariatur"
},
],
"occurrence": [
"Music",
"Party"
]
}
};
I would like to explicitly use a for loop as per the code below (and not for in)
for(var i = 0; i < json.length; i++) {
console.log(json.tsn.events[i].title);
}
Why does the above code does not get all of title?
Secondly, how should I get all the occurrence?
And lastly, how I can add to events a new key/value pair such as {"image": "cat.jpg"} so that the json object results like this:
var json = {"tsn": {
"events": [
{
"title": "Lorem ipsum",
"description": "Dolor sit",
"image": "cat.jpg"
},
{
"title": "Duis aute irure",
"description": "eu fugiat nulla pariatur",
"image": "dog.jpg"
},
],
"occurrence": [
"Music",
"Party"
]
}
};
forloop is for arrays - you have an object, one of the keys in your object contains an array, so iterate over that key.for (var i = 0; i < json.tsn.events.length; i++)