Reputation: 153
How to split data in JSON if have array after array? This is my JSON format
{
"status": "true",
"error": "",
"data": [
{
"id": 1,
"sections": [
{
"section_id": 1,
"position": []
}
]
}
]
}
So, I'm using AXIOS . This code AXIOS
const url = '/api/v1/form/'
axios
.get(url)
.then(response => {
this.listing = response.data.data;
})
How to call section using this response.data.data.sections
? I'm try but error undefined. Please help me thanks
Upvotes: 0
Views: 694
Reputation: 324
Try this:
const url = '/api/v1/form/'
axios
.get(url)
.then(response => {
this.listing = response.data;
console.log(this.listing.data) // <-------
})
Upvotes: 0
Reputation: 386
response.data.data[0].sections
data
is an array according to your json so you cannot directly call sections you will have to iterate or select an instance within the array.
the following code should print all section ids //untested code
const url = '/api/v1/form/'
axios
.get(url)
.then(response => {
response.data.data.foreach((listing)=>{
console.log(listing.sections.section_id)
})
})
If you always will have only one entry under data
or you want to access only the 1st entry of data
you can use response.data.data[0].sections
this is a bad way to access it though because if data is empty it will throw you an error . If the case is that you only have one entry under data
you should just change your json to be
{
"status": "true",
"error": "",
"data":
{
"id": 1,
"sections": [
{
"section_id": 1,
"position": []
}
]
}
}
and you can then access it directly response.data.data.sections
but as long as its an array you will have to treat it as such.
Iterate through sections and positions [as per comments]:
const url = '/api/v1/form/'
axios
.get(url)
.then(response => {
response.data.data.foreach((listing)=>{ //#this will get you each listing(parent object that contains sections array)
listing.sections.foreach((section)=>{//# this will get you each section(parent object that contains position array)
section.position.foreach((el)=>{//# this will get you each elment in the position array as `el`
console.log(el)
})
})
})
})
Upvotes: 2