Get child inside child in JSON / Iterate via nested JSON using jQuery / JS?
I wonder if this is possible if so how can I get through this:
[
{
"name": "Hello",
"views": 10,
"subMovie": [
{
"name": "World",
"views": 10,
"subMovie": [
{
"name": "Test 1",
"views": 10,
"subMovie": [
{
"name": "Test 2",
"views": 10,
"subMovie": [
{
"name": "Test 3",
"views": 10,
"subMovie": [],
"id": 5
}
],
"id": 4
}
],
"id": 3
}
],
"id": 2
}
],
"id": 1
}
]
to go to the last child (subMovie)?
I want to access all and print them, but how do I scroll this child inside the child using jQuery / JavaScript?
source to share
The following code will start from the last element of the array movies
. After that, it will descend into the tree subMovie
, selecting the last element of the array of each visited movie until it remains subMovie
.
var movies = [
{
"name": "Hello",
"views": 10,
"subMovie": [
...
],
"id": 1
}
];
var m = movies[movies.length - 1];
while(m.subMovie.length >= 1) {
console.log(m.name);
m = m.subMovie[m.subMovie.length - 1];
}
console.log(m); //Object {name: "Test 3", views: 10, subMovie: Array[0], id: 5}
source to share
It's not a single JSON object. You have arrays containing JSON objects. if you want to know more about JSON check out this article .
Given that your array has a name data
like below:
var data = [
{
"name": "Hello",
"views": 10,
"subMovie": [
{....
}
]
Using the following code:
data[0].subMovie[0].subMovie[0].subMovie[0].subMovie[0];
This will return:
Object {name: "Test 3", views: 10, subMovie: Array[0], id: 5}
Hope it helps.
source to share