![]() |
JavaScript allows us to push an object into an array using a for-loop. This process consists of iterating over the sequence of values or indices using the for-loop and using an array manipulation method like push(), to append new elements to the array. We have given an empty array, and we need to push the object into the array. Below is an example for a better understanding of the problem statement. Table of Content Using simple for-loopThis method uses a simple for-loop to push the array object into the array. We are printing the array before pushing of object and also printing the array after pushing the object into the array. Syntax:for (initialization; condition; update) { Example: The below code uses a simple for-loop to push an object into an array using a for-loop in JavaScript. Javascript
Output
Array before pushing: [] Array after pushing: [ { title: 'Introduction to JavaScript', author: 'Geek123', views: 1000 } ] Using for…of LoopThis method uses for…of loop to push the objects into an array where the array is initially empty. The for of loop iterates over the array to push the objects into the array. Syntax:for (variable of iterable) { Example: The below code uses for…of Loop to push an object into an array using a for-loop in JavaScript. Javascript
Output
Array before pushing: [] Array after pushing: [ { title: 'Introduction to JavaScript', author: 'Geek123', views: 1000 } ] Using forEach LoopThis method uses the forEach loop, there is an empty array arr and the arrObj. When the forEach loop is executed, the loop pushes the object into the array and the array is been updated with the object which is been pushed. We are printing the array as output. Syntax:array.forEach(function(currentValue, index, array) { Example: The below code uses a forEach Loop to push an object into an array using a for-loop in JavaScript. Javascript
Output
Array before pushing: [] Array after pushing: [ { title: 'Introduction to JavaScript', author: 'Geek123', views: 1000 } ] |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |