Reputation: 128
I'm trying to iterate through a nested array object like below. What is the best way to access each of the object elements within the nested arrays.
{
"titleId": "111G",
"aNumber": "1212",
"data": [{
"id": "6657",
"name": "test name",
"city": "LA",
"state": "CA",
"comment": "comment 1",
"dates": [{
"startDate": "01/17/2020",
"endDate": "01/22/2020"
},
{
"startDate": "01/24/2020",
"endDate": "01/30/2020"
}
]
},
{
"id": "123",
"name": "abc",
"city": "NJ",
"state": "NY",
"comment": "comment 2",
"dates": [{
"startDate": "01/17/2020",
"endDate": "01/22/2020"
},
{
"startDate": "01/24/2020",
"endDate": "01/30/2020"
}
]
}
]
}
I need to access each of the elements in data and the dates array as well
Upvotes: 0
Views: 212
Reputation: 10719
const info = {
"titleId": "111G",
"aNumber": "1212",
"data": [{
"id": "6657",
"name": "test name",
"city": "LA",
"state": "CA",
"comment": "comment 1",
"dates": [{
"startDate": "01/17/2020",
"endDate": "01/22/2020"
},
{
"startDate": "01/24/2020",
"endDate": "01/30/2020"
}
]
},
{
"id": "123",
"name": "abc",
"city": "NJ",
"state": "NY",
"comment": "comment 2",
"dates": [{
"startDate": "01/17/2020",
"endDate": "01/22/2020"
},
{
"startDate": "01/24/2020",
"endDate": "01/30/2020"
}
]
}
]
}
info.data.forEach(city => city.dates.forEach(cityDate => console.log(cityDate.startDate)))
Upvotes: 0
Reputation: 11
if I understand the question correctly you want to iterate over the dates array inside of each item in the data item, this is how I would do it in js
var date = JSON.parse(res.data)
date.forEach(element => {
var items = element.dates
items.forEach(current => {
//do whatever
});
});
Upvotes: 1