How to store multiple objects in array in JavaScript
To store multiple objects in an array in JavaScript, you can simply define the objects and push them into the array using the push() method. The example is given below.
<script> let obj1 = {name: "Red", code: "#ff0000"}; let obj2 = {name: "Yellow", code: "#ffff00"}; let obj3 = {name: "Black", code: "#000000"}; let objArray = []; objArray.push(obj1); objArray.push(obj2); objArray.push(obj3); console.log(objArray) </script>
In the above example, we define three objects, obj1, obj2, and obj3. Then, We define an empty array objArray, and push the three objects into it using the push() method. Now objArray contains all three objects.
Now if you want to access the properties of the objects, you can use the following code.
<script> console.log(objArray[0].name); // Output: "Red" console.log(objArray[1].code); // Output: "#ffff00" </script>
How to store multiple objects in array in JavaScript #
- Create an empty array and define some objects.
<script> let objArray = []; let obj1 = {name: "Red", code: "#ff0000"}; let obj2 = {name: "Yellow", code: "#ffff00"}; let obj3 = {name: "Black", code: "#000000"}; </script>
- Push the objects into the array.
<script> objArray.push(obj1); objArray.push(obj2); objArray.push(obj3); </script>
- Alternatively, you can directly define the objects inside the array.
<script> let objArray = [ {name: "Red", code: "#ff0000"}, {name: "Yellow", code: "#ffff00"} ]; </script>
- To add multiple objects at once, you can use the spread operator with the push() method.
<script> let obj1 = {name: "Red", code: "#ff0000"}; let obj2 = {name: "Yellow", code: "#ffff00"}; let objArray = []; objArray.push(...[obj1, obj2]); </script>
save
listen
AI Answer
How to store multiple objects in array in JavaScript
0
To store multiple objects in an array in JavaScript, you can simply define the objects an…
asked
Apu
0 answers
2915
To store multiple objects in an array in JavaScript, you can simply define the objects an…
Answer Link
answered
Apu