Nancy
Nancy

Reputation: 1051

Can't access data. object in another object?

This is the data in question

[ 
    { 
        "id":1,
        "date":"2020-01-02",
        "start_time":"11:32:25",
        "end_time":"11:32:26",
        "editions":null,
        "coordinates":null,
        "ranking":null,
        "user_id":3,
        "instructor_id":2,
        "course_id":2,
        "package_id":null,
        "location_id":3,
        "created_at":null,
        "updated_at":null,
        "student_schedules":[ 
            { 
                "id":1,
                "student_schedule_id":1,
                "calification":75,
                "approved":0
            }
        ],
    }
]

I'm trying to get to calification in student_schedules. I've tried doing the following, the history is the entire data

history.student_schedules['calification']

history.student_schedules.calification

This doesn't work and gives me errors

TypeError: Cannot read property 'calification' of undefined

[Vue warn]: Error in render: "TypeError: Cannot read property 'calification' of undefined"

I don't know why these errors are happening, the data is clearly there.

How can I access this data?

Upvotes: 0

Views: 73

Answers (2)

tosi
tosi

Reputation: 621

Both history and student_schedules are arrays which can contain multiple objects. If you want to access an object of an array you need to specify it's index, for example:

history[0].student_schedules[0].clarification

If the arrays will only contain one object then you can remove the []

{ 
    "id":1,
    "date":"2020-01-02",
    "start_time":"11:32:25",
    "end_time":"11:32:26",
    "editions":null,
    "coordinates":null,
    "ranking":null,
    "user_id":3,
    "instructor_id":2,
    "course_id":2,
    "package_id":null,
    "location_id":3,
    "created_at":null,
    "updated_at":null,
    "student_schedules":
        { 
            "id":1,
            "student_schedule_id":1,
            "calification":75,
            "approved":0
        }
}

and then access the data like so:

history.student_schedules.clarification

Upvotes: 0

T. Short
T. Short

Reputation: 3614

history is an array of objects.

So you would first need to target the first object in the array with history[0]

Then, student_schedules is also an array of objects, so you have to do the same thing there and you end up with:

history[0].student_schedules[0].calification

You can tell the difference between an object and an array with {} and [] respectively.

Upvotes: 1

Related Questions