-1

I have a json file in a structure like this one:

{

"items":[
    {
        "username":"abc",
        "orderID":"1234",
        "commentHistory":[
            {
                "comment":"Comment Date: 2016/12/09 13:44:23"
            },
            {
                "comment":"Failed: 2016/12/08 11:42:12"
            }
        ],
        .........
    }
]}

Where an array "items" is storing the data and there is another array inside to store the comment history. I know I can get the data using JSON.parse, like the example from W3School (http://www.w3schools.com/js/tryit.asp?filename=tryjs_json_parse).

However, the example only including one array in it. So if I want to get the data inside the second array, ie: comment inside comment history... how the syntax would look like if I want to access the data of an array inside another array? Thank you so much.

Sammi
  • 261
  • 5
  • 20

1 Answers1

1

Not much syntax at all. This code should work for any number of comments within a given history.

JSON.parse(jsonString).items[0].commentHistory.map(function (e) {
    return e.comment
})

Here's a snippet so you can see for yourself:

var data = {

"items":[
    {
        "username":"abc",
        "orderID":"1234",
        "commentHistory":[
            {
                "comment":"Comment Date: 2016/12/09 13:44:23"
            },
            {
                "comment":"Failed: 2016/12/08 11:42:12"
            }
        ],
    }
]}

console.log(data.items[0].commentHistory.map(function (e) {
    return e.comment
}))
gyre
  • 16,369
  • 3
  • 37
  • 47