0

I have javascript object like follows:

var school = {
    grade1:[
    {
    "teacher":"anna",
    "student":"jacky"
    },
    {..},...
    ]
    grade2:[...]   
}

I ran into a problem as I tried to retrieve content using a function

function getNames(grade){
    $('#demo').text(school.grade[0].teacher); //returns an error
}

I could use school.grade1[0].teacher but I want to have a grade variable.

As I tried this and it obviously doesn't work:

var grade = 'grade1'; //I also tried just grade1 but it is an undefined varaible
getNames(grade); 
  • Where going to need to see a working example. There are lots of things we need to know such as: is jQuery defined and where is `school.grade` defined? What is the error message? etc... But I don't think jQuery is needed in this example. – Spencer Wieczorek Nov 20 '15 at 05:02

2 Answers2

1

You can do

school[grade][0].teacher
Thilo
  • 257,207
  • 101
  • 511
  • 656
0

You can try like this:

function getNames(grade){
    $('#demo').text(grade.teacher);
}

var grade = school.grade1[0]
or
var grade = school.grade2[0]
getNames(grade);