Joshua Velez
Joshua Velez

Reputation: 23

Pulling array from object

Im trying to pull the gpa numbers from the array that is in the object and have them displayed in the console but my code keeps giving me undefined '0' error. Any help would be appreciated.

var fsInfo = {
    name: 'John Doe',
    address:{
        street: '123 Some Street ',
        city: 'Town, ',
        state: 'HI',
    gpa: [3.0,4.0,2.0]
    }
 }

console.log("GPA: " + fsInfo.gpa['0'],fsInfo.gpa['1'],fsInfo.gpa['2'])

Upvotes: 1

Views: 69

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

Use

console.log("GPA: " + fsInfo.gpa[0],fsInfo.gpa[1],fsInfo.gpa[2])

Note: Array indices are numbers.

In your case, they are inside address. So you should do

console.log("GPA: " + fsInfo.address.gpa[0],fsInfo.address.gpa[1],fsInfo.address.gpa[2])

If your object had been like this

var fsInfo = {
    name: 'John Doe',
    address:{
        street: '123 Some Street ',
        city: 'Town, ',
        state: 'HI'
    },
    gpa: [3.0,4.0,2.0]
 }

then

console.log("GPA: " + fsInfo.gpa[0],fsInfo.gpa[1],fsInfo.gpa[2])

will work.

Upvotes: 1

Related Questions