Monday, February 4, 2019

iterating through json object javascript

My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.



{
"dialog":
{
"trunks":[

{
"trunk_id" : "1",
"message": "This is just a JSON Test"
},
{
"trunk_id" : "2",
"message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
}
]
}

}


At that point, I was able to do a fairly simple for loop based on the total number of objects.



var totalMessages = Object.keys(messages.dialog.trunks).length;

for ( var i = 0; i < totalMessages; i++)
{
console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);

}


My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...