Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access array inside an object

 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

like image 963
Saurya Avatar asked Oct 28 '25 14:10

Saurya


2 Answers

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
like image 61
Jonathan Muller Avatar answered Oct 31 '25 04:10

Jonathan Muller


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
like image 22
bln Avatar answered Oct 31 '25 06:10

bln



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!