Skip to content

Array inside object JavaScript

  • by

You can use Array inside object JavaScript. Not even Array anything inside JavaScript objects, including other objects, functions, etc can define.

An array is an object, and you can have an object as a property of another object.

Array inside object JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

    var office = {
     name: 'ABC',
     city: 'Bangalore',
     weekdays: ['sun','mon','tue','wed','thu','fri','sat']
   };

   console.log(office)

 </script>

</body>
</html> 

Output:

Array inside object JavaScript

Access array inside an object


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

How to push an array into the object in JavaScript?

Answer: An array can be inserted into the object with the push() function

  <script>

    var Obj = {             
      arrayOne: [],
      arrayTwo: []
    };

    var arraynew = ['A', 'B', 'C'];
    Obj.arrayOne.push(arraynew);     

    console.log(Obj);

  </script>

.Output:

arrayOne: Array [ (3) […] ]
​​
0: Array(3) [ "A", "B", "C" ]

arrayTwo: Array []

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading