How to access object inside nested array?

How to access object inside nested array?
0

#1

Hi there,

I have an array, called movies. As you can see below, it consist of two elements:

One element consist of 20 objects.

There is a key that I would like to access it, the name of the key is id and the value is 412121

How do I access that particular key to retrieve the value of the key?

Thanks


#2

you can use syntax array[0][0].id


#3

I agree with @computerluca


#4

Hi @computerluca and @verv0eren,

I assign it to var called a:

var a = movies[0][0].id;

I still don’t know how to access that particular key (id) with certain value (412121). I really appreciate your help.


#5

This is my code, you can get your own API key from themoviedb.org

var movies = [];
var request = new XMLHttpRequest();

request.open(‘GET’, ‘https://api.themoviedb.org/3/movie/now_playing?api_key=MYAPIKEY&page=12’);

request.onreadystatechange = function () {
if (this.readyState === 4) {
let moviesPage = JSON.parse(this.responseText);
movies.push(moviesPage.results);
}
};
request.send();

var request = new XMLHttpRequest();

request.open(‘GET’, ‘https://api.themoviedb.org/3/movie/now_playing?api_key=MYAPIKEY&page=13’);

request.onreadystatechange = function () {
if (this.readyState === 4) {
let moviesPage = JSON.parse(this.responseText);
movies.push(moviesPage.results);
}
};
request.send();
console.log(movies);
var a = movies[0][0].id;


#6

Can we see the JSON file?


#7

sure, this is taken from page 7, my array, which is movies is the result from movies.push(moviesPage.results); and moviesPage is from let moviesPage = JSON.parse(this.responseText);

you can generate this if you register and obtain api key from http://docs.themoviedb.apiary.io/#reference/movies/movienowplaying

{
“page”: 7,
“results”: [
{
“poster_path”: null,
“adult”: false,
“overview”: “”,
“release_date”: “2016-09-01”,
“genre_ids”: [],
“id”: 409304,
“original_title”: “Deserto”,
“original_language”: “pt”,
“title”: “Deserto”,
“backdrop_path”: null,
“popularity”: 1.7676,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: null,
“adult”: false,
“overview”: “”,
“release_date”: “2016-09-01”,
“genre_ids”: [],
“id”: 409312,
“original_title”: “O Último Trago”,
“original_language”: “pt”,
“title”: “O Último Trago”,
“backdrop_path”: null,
“popularity”: 1.7676,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: “/yB3XxIsxWPZgEX2FDwRI3HpSbn9.jpg”,
“adult”: false,
“overview”: “”,
“release_date”: “2016-08-31”,
“genre_ids”: [
18
],
“id”: 382503,
“original_title”: “Le fils de Jean”,
“original_language”: “fr”,
“title”: “Le fils de Jean”,
“backdrop_path”: “/pnd2ZaF7MBUdan4EZyYY1MRkaaH.jpg”,
“popularity”: 1.74802,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: “/7UYtebfedwmXQmZM8jTipjJcBdp.jpg”,
“adult”: false,
“overview”: “After an unprecedented global pandemic has turned the majority of humankind into violent “Infected,” a man gifted with the ability to speak the Infected’s new language leads the last survivors on a hunt for Patient Zero and a cure.”,
“release_date”: “2016-08-25”,
“genre_ids”: [
53,
28,
27
],
“id”: 295011,
“original_title”: “Patient Zero”,
“original_language”: “en”,
“title”: “Patient Zero”,
“backdrop_path”: null,
“popularity”: 1.72296,
“vote_count”: 1,
“video”: false,
“vote_average”: 10
},
{
“poster_path”: “/wIbaQQ6KChqSEDAcoB97IHarvET.jpg”,
“adult”: false,
“overview”: “Ryohei is a writer who drives the characters in his novels into a corner to make a tragic story comes to Seoul for a book launching event. The day he arrives in Seoul, he meets Eunhee, a woman in trouble just like in his novel. A movie that takes a delicate look at the sensitivity of characters.”,
“release_date”: “2016-08-25”,
“genre_ids”: [
18,
10749
],
“id”: 398246,
“original_title”: “최악의 하루”,
“original_language”: “ko”,
“title”: “Worst Woman”,
“backdrop_path”: null,
“popularity”: 1.718266,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: “/hPrccfqOfB36XHpw3NTY8XMgWIK.jpg”,
“adult”: false,
“overview”: “In 2011 Portugal began the so-called “year of the Troika” (EU, IMF and ECB budget cuts and economic restructuring), with the level of debt among the Portuguese people reaching staggering amounts and a growing number of families and companies unable to repay their installment loans. Jorge is an unemployed boxer on the verge of losing his son and his wife, who has decided to return to Brazil. As a means of paying off his debt and persuading his wife to remain in Portugal, Jorge accepts a job with a debt-collection agency, which will drag him into a world of violence and crime.”,
“release_date”: “2016-08-31”,
“genre_ids”: [],
“id”: 412660,
“original_title”: “São Jorge”,
“original_language”: “en”,
“title”: “São Jorge”,
“backdrop_path”: “/cViw5Sta2wsVpsUCbfygaNU0wNQ.jpg”,
“popularity”: 1.713941,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: “/vH2PXMTHLjRX1KkfMqFFTNfDW5b.jpg”,
“adult”: false,
“overview”: “A Yorkshire Terrier, competing in a televised singing competition, is separated from her owner by an opportunist dog pound worker.”,
“release_date”: “2016-08-30”,
“genre_ids”: [],
“id”: 413221,
“original_title”: “Pup Star”,
“original_language”: “en”,
“title”: “Pup Star”,
“backdrop_path”: null,
“popularity”: 1.675017,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: “/cD7N6mUfFNUgb5Wk4s7TEteB5Nb.jpg”,
“adult”: false,
“overview”: “A contemporary musical version of the classic Cinderella story in which the servant step daughter hope to compete in a musical competition for a famous pop star.”,
“release_date”: “2016-08-02”,
“genre_ids”: [
35,
10402
],
“id”: 407655,
“original_title”: “A Cinderella Story: If the Shoe Fits”,
“original_language”: “en”,
“title”: “A Cinderella Story: If the Shoe Fits”,
“backdrop_path”: “/svYzELCLW0NGVEuvNraA4W7Hmm9.jpg”,
“popularity”: 1.671653,
“vote_count”: 4,
“video”: false,
“vote_average”: 5
},
{
“poster_path”: “/qqJxgv5ruODqtbj8wKbGBFMR6ko.jpg”,
“adult”: false,
“overview”: “”,
“release_date”: “2016-08-31”,
“genre_ids”: [
18
],
“id”: 413576,
“original_title”: “1/1”,
“original_language”: “en”,
“title”: “1/1”,
“backdrop_path”: null,
“popularity”: 1.657618,
“vote_count”: 1,
“video”: false,
“vote_average”: 6
},
{
“poster_path”: “/wxhYcSjzfIdaQwckGvapS7Mqlh4.jpg”,
“adult”: false,
“overview”: “Debbie Taylor is a former 1980s pop star bent on making a comeback and returning to the Billboard charts. As she prepares to once again take the music industry by storm, Debbie’s record label deems her irrelevant and abruptly drops her. Out of money, she leaves the fast lane of New York to move in with her sister in Youngstown, Ohio.”,
“release_date”: “2016-08-27”,
“genre_ids”: [
10770,
18,
10751
],
“id”: 411082,
“original_title”: “Summer of Dreams”,
“original_language”: “en”,
“title”: “Summer of Dreams”,
“backdrop_path”: “/azsG55Dn0Jlb9VKQuMwiyqRBv0.jpg”,
“popularity”: 1.653293,
“vote_count”: 1,
“video”: false,
“vote_average”: 6
},
{
“poster_path”: “/7RxMSqAt6PybjYW67wVXvlvjxc6.jpg”,
“adult”: false,
“overview”: “”,
“release_date”: “2016-08-26”,
“genre_ids”: [
35
],
“id”: 375872,
“original_title”: “Cuerpo de élite”,
“original_language”: “es”,
“title”: “Heroes Wanted”,
“backdrop_path”: “/50v91dgENRiqHpUu1mJBLzU6LsS.jpg”,
“popularity”: 1.645917,
“vote_count”: 1,
“video”: false,
“vote_average”: 6
},
{
“poster_path”: “/EyKSq0GGmqqyAz1SDgYZNoFlMK.jpg”,
“adult”: false,
“overview”: “A group of brokenhearted women end up at a resort that specializes in helping people ease their pain.”,
“release_date”: “2016-08-24”,
“genre_ids”: [],
“id”: 413192,
“original_title”: “Camp Sawi”,
“original_language”: “en”,
“title”: “Camp for the Broken-Hearted”,
“backdrop_path”: null,
“popularity”: 1.641058,
“vote_count”: 1,
“video”: false,
“vote_average”: 10
},
{
“poster_path”: “/8vtBH6aoWxeocQKGFK4O3zV699g.jpg”,
“adult”: false,
“overview”: “Just outside Philadelphia is a suburb full of trust fund kids and bored old men. In the heart of that suburb is a brothel run by women who are nothing more than a rite of passage to those men. House of Little Deaths explores every thing they do to get through a day, everything they hope for, everything they want to forget, everything they do to escape. A film about the mundane and bitter truth behind a world of fantasy.”,
“release_date”: “2016-08-31”,
“genre_ids”: [
18
],
“id”: 413649,
“original_title”: “House of Little Deaths”,
“original_language”: “en”,
“title”: “House of Little Deaths”,
“backdrop_path”: null,
“popularity”: 1.639457,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: “/mxyosE7j1ilAYPpHP92cfSjTEou.jpg”,
“adult”: false,
“overview”: “It’s pedal to the metal as Scooby-Doo, Shaggy and the gang team up with the superstars of WWE in this hi-octane, all-new original movie! When Scooby and Mystery Inc. visit an off-road racing competition, it’s not long before strange events start to occur. A mysterious phantom racer, known only as Inferno, is causing chaos and determined to sabotage the race. It’s up Scooby-Doo, Shaggy and their new driving partner, The Undertaker, to save the race and solve the mystery. Along with other WWE superstars such as Triple H, Paige and Shamus, it’s time to start your engine and your appetite because Scooby-Doo and WWE are chasing down adventure and laughs just for you!”,
“release_date”: “2016-08-09”,
“genre_ids”: [
16
],
“id”: 409122,
“original_title”: “Scooby-Doo! And WWE: Curse of the Speed Demon”,
“original_language”: “en”,
“title”: “Scooby-Doo! And WWE: Curse of the Speed Demon”,
“backdrop_path”: “/lmiFdQ2uiYvdrKHo7frSXegjCVV.jpg”,
“popularity”: 1.629878,
“vote_count”: 6,
“video”: false,
“vote_average”: 7.33
},
{
“poster_path”: “/csIv174a6GlCiiLQ9GkcwGPWtNN.jpg”,
“adult”: false,
“overview”: “Aspiring New York City artist John Hollar returns to his Middle America hometown on the eve of his mother’s brain surgery. Joined by his girlfriend, eight months pregnant with their first child, John is forced to navigate the crazy world he left behind.”,
“release_date”: “2016-08-25”,
“genre_ids”: [
10751,
35,
18
],
“id”: 325346,
“original_title”: “The Hollars”,
“original_language”: “en”,
“title”: “The Hollars”,
“backdrop_path”: “/ppS1d0xXbkgUpuGU7rX5BLyjm5H.jpg”,
“popularity”: 1.626362,
“vote_count”: 8,
“video”: false,
“vote_average”: 4.25
},
{
“poster_path”: “/6xNZDJpsLWZlBNWeq9ABCzGx5wP.jpg”,
“adult”: false,
“overview”: “A wealthy developer tries to remove settlers from his newly acquired land, which leads to dire consequences.”,
“release_date”: “2016-08-28”,
“genre_ids”: [
14,
27,
53
],
“id”: 408387,
“original_title”: “Crow”,
“original_language”: “en”,
“title”: “Crow”,
“backdrop_path”: null,
“popularity”: 1.623247,
“vote_count”: 1,
“video”: false,
“vote_average”: 1
},
{
“poster_path”: “/nmjlFuu2mUT2eUvn8wINOgM3cys.jpg”,
“adult”: false,
“overview”: “While on a fourth of July holiday, six best friends fall victim to the insidious plan of a terrorist organization when they unknowingly take a bio-active drug that transforms them into bloodthirsty cannibals.”,
“release_date”: “2016-08-29”,
“genre_ids”: [
27
],
“id”: 396004,
“original_title”: “The Evil in Us”,
“original_language”: “en”,
“title”: “The Evil in Us”,
“backdrop_path”: null,
“popularity”: 1.621025,
“vote_count”: 1,
“video”: false,
“vote_average”: 6
},
{
“poster_path”: “/7AmYRONggQatbCkYX75yGuRmTJY.jpg”,
“adult”: false,
“overview”: “On the isolated grasslands of Inner Mongolia, a shepherdess adopts an orphan from the city. Years later after the boy has left to serve in the air force, a well-intentioned white lie gives the elderly shepherdess hope of seeing her adopted son one last time.”,
“release_date”: “2016-08-29”,
“genre_ids”: [
10769,
18
],
“id”: 413371,
“original_title”: “母亲的飞机场”,
“original_language”: “zh”,
“title”: “Mother’s Airfield”,
“backdrop_path”: null,
“popularity”: 1.620347,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: “/7JjkyMjeOZSPwBBxqw9N5rea3i5.jpg”,
“adult”: false,
“overview”: “When an ex-CIA agent discovers his family have been kidnapped he sets out to rescue them, only to discover they are being held hostage and won’t be released unless he carries out a mission to assassinate the President. He must use his advanced skills to outwit the men holding his family and prevent the assassination from going ahead before the clock runs out for his family.”,
“release_date”: “2016-08-29”,
“genre_ids”: [],
“id”: 412431,
“original_title”: “Decommissioned”,
“original_language”: “en”,
“title”: “Decommissioned”,
“backdrop_path”: null,
“popularity”: 1.612114,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
},
{
“poster_path”: “/hI6RC5uGnDUjWVwTX8jeICYA3xV.jpg”,
“adult”: false,
“overview”: “Struggling manga author Satoru Fujinuma is beset by his fear to express himself. However, he has a supernatural ability of being forced to prevent deaths and catastrophes by being sent back in time before the incident occurred, repeating time until the accident is prevented. One day, he gets involved in an accident that has him framed as a murderer. Desperate to save the victim, he sends himself back in time only to find himself as a grade-schooler one month before fellow classmate Kayo Hinazuki went missing. Satoru now embarks on a new quest: to save Kayo and solve the mystery behind her disappearance.”,
“release_date”: “2016-08-18”,
“genre_ids”: [
53,
14
],
“id”: 379300,
“original_title”: “僕だけがいない街”,
“original_language”: “ja”,
“title”: “Erased”,
“backdrop_path”: “/rDP3bdj9Vt2h1qGMaE28XZvDP4i.jpg”,
“popularity”: 1.611043,
“vote_count”: 0,
“video”: false,
“vote_average”: 0
}
],
“dates”: {
“maximum”: “2016-09-05”,
“minimum”: “2016-07-25”
},
“total_pages”: 34,
“total_results”: 675
}


#8

you have to put something like this:
var a = json.results[0].id;
There is no array named “movies” in the data.


#9

actually I created an empty array called movies. (You can see it in my 3rd post above).

var movies = [];

after that I created an object called moviesPage which is contail all JSON file from every pages.

let moviesPage = JSON.parse(this.responseText);

and then I push the content of moviesPage result to my array, movies.

My goal is I want to collect every value that contain in id key for every pages.


#10

Actually, I am also a beginner. So I don’t know that much deeply.


#11

no worries @verv0eren, thank you.

Well, hopefully I can finish this task. I am trying to finish random quote machine project, but I prefer to use this API in order to generate movies plot, actors etc.


#12

I have just finished my Random Quote project yesterday. Now working on the weather app.


#13

here is a repel i did for you … go to link hit run and it lists all the ids … scroll to the end to see the code
adjust the code then to sort your needs.


#14

Hi @JohnL3, wow. Thank you very much. I really appreciate it.


#15

I figure it out the answers:

To retrieve value of 412121 from key called id =

movies[0].results[0].id;


#16

Lesson learned.

I won’t be able to access array immediately after it executed. I need to introduce delay for around 1000 ms / 1 seconds (it could be lower than that) but this is not urgent/vital application, so I just use 1 seconds delay.

setTimeout(function() {
console.log(movies);
var a = movies[0][0].id;
var b = movies[0][1].id;
var c = movies[1][0].id;
var d = movies[1][1].id;
// },1000);

@computerluca is giving the right answer in 2nd post above, but due to the need of delay, the script must wait before trying to execute movies[0][0].id

Thanks folks for all your assistance. Keep the spirit up!


#17

I use this JSON beautifier http://jsonmate.com.

It is great for accurately finding object keys…


#18

Also http://jsonviewer.stack.hu/ is good. Shows JSON in tree structure.


#19

@harsiandy As you said, the problem was that you ere trying to access the response from the API before you had it.

Why is that happening?

  • JS exectues line after line
  • A get request is an asynchronous piece of code.

With that in mind, the part of your code request.onreadystatechange is going to be executed when you have received the answer, that means at some point in the future. Not following the secuencial order of the program. Therefore with your timeout, what you are donig is executing that code also at some point in the future.

Instead of using the timeout, why don’t you do the initialization and assignation of the var a inside the request.onreadystatechange.

Hope it helps!