5
 var b = {
  maths:[12,23,45],
  physics:[12,23,45],
  chemistry:[12,23,45]
};

I want to access array in object b. ie, maths, physics, chemistry . This may be a simple question but i am learning....Thanks

Wenbing Li
  • 10,922
  • 1
  • 28
  • 41
Saurya
  • 61
  • 1
  • 1
  • 6

5 Answers5

5

Given the arrays in the object b (note that you have a syntax error in the code you provided)

var b = {
  maths: [12, 23, 45],
  physics: [12, 23, 45],
  chemistry: [12, 23, 45]
};

maths, physics, and chemistry are called properties of the object stored in variable b

You can access property of an object using the dot notation:

b.maths[0]; //get first item array stored in property maths of object b

Another way to access a property of an object is:

b['maths'][0]; //get first item array stored in property maths of object b
Jonathan Muller
  • 7,079
  • 2
  • 21
  • 29
4
var b = {
    maths:[12,23,45],
    physics:[12,23,45],
    chemistry:[12,23,45]
};

console.log(b.maths);
// or
console.log(b["maths"]);
// and
console.log(b.maths[0]); // first array item
bln
  • 290
  • 1
  • 5
1
var b = {
    maths:[12,23,45],
    physics:[12,23,45],
    chemistry:[12,23,45]
};

// using loops you can do like
for(var i=0;i<b.maths.length;i++){
      console.log(b.maths[i]);//will give all the elements
}
Roli Agrawal
  • 2,186
  • 3
  • 21
  • 27
0

there are simple:

b = {
      maths:[12,23,45],
      physics:[12,23,45],
      chemistry:[12,23,45]
    };

b.maths[1] // second element of maths
b.physics
b.chemistry
Legendary
  • 2,262
  • 15
  • 26
0

You need to set the variable b like this :

var b = {
  maths:[12,23,45],
  physics:[12,23,45],
  chemistry:[12,23,45]
};

Then you can access your arrays inside b by using b.maths, b.physics and b.chemistry.

Bast Ounet
  • 11
  • 1