How to push an array into the object in JavaScript ?

In order to push an array into the object in JavaScript, we need to utilize the push() function. With the help of Array push function this task is so much easy to achieve.

push() function: The array push() function adds one or more values to the end of the array and returns the new length. This method changes the length of the array. But here we will use this function to push the whole array into an object.

Syntax:



arr.push(element1[, ...[, elementN]])

An array can be inserted into the object with push() function, below examples illustrate the above approach:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// JavaScript program to add array into
// an object using push() function
  
// Creating a JS object to add array into it
var Obj = {             
    arrayOne: [],
    arrayTwo: []
};
  
// Array to be inserted
var arraynew = ['Geeks', 'for', 'Geeks'];
  
// Push an array to object
Obj.arrayOne.push(arraynew);     
  
alert(Obj.arrayOne);
      
</script>                     

chevron_right


Output:
Output after inserting array

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// JavaScript program to add array into
// an object using push() function
  
// Creating a JS object to add array into
var Obj = {             
    arrayOne: ['Geeks', 'for', 'Geeks'],
    arrayTwo: []
};
  
// Array to be inserted
var arraynew = ['Hello', 'World', '!!!']; 
  
// Pushing of array into arrayTwo
Obj['arrayTwo'].push(arraynew);     
  
alert(Obj.arrayTwo);
      
</script>                    

chevron_right


Output:
Output after inserting array2

Supported Browsers: The supported browser by the Array Push() Function are listed below:

  • Google Chrome 1.0
  • Internet Explorer 5.5
  • Mozila Firefox 1.0
  • Safari
  • Opera


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.