Enzio
Enzio

Reputation: 889

Javascript : I cannot access JSON objects inside an array using array index

database.ref().once("value", function (snap) {
    scores = snap.val();
    console.log(scores);
    console.log(scores[1]);
});

enter image description here

scores is an array of JSON objects taken from a firebase database.

However, I cannot access the objects inside the array.

I assume that scores[1] would print.

-L1qn0mBwpny-7FVzlCF : {Name: "Josh", Score: 9}

But it prints undefined.

Upvotes: 0

Views: 148

Answers (1)

31piy
31piy

Reputation: 23859

No, it won't print it because scores is a JavaScript object, and not an array. Plus, there is no key 1 in that object.

To get the underlying object of key -L1qn0mBwpny-7FVzlCF, you need to access it like this:

scores['-L1qn0mBwpny-7FVzlCF'] // { "Name": "Josh", "Score": 9 }

Upvotes: 2

Related Questions