In this article, we will learn to create an array with multiple objects having key-value pairs, we will use nesting which means defining another array in a pre-defined array with key-value pairs.
Suppose we have several arrays of objects means containing various key-value pairs where keys are uniquely identified now we have to add these arrays to another array called the base or parent array. Let’s do this with an example.
Example 1: Creating the array containing key-value pair objects.
Javascript
<script> const array1 = [ { key : 1 , value : "hello" } , { key : 2 , value : "Geek" } , { key : 3 , value : "neveropen" } , { key : 4 , value : "JavaScript" } , { key : 5 , value : "Course" } ]; console.log(array1); </script> |
Output:
[ { key: 1, value: 'hello' }, { key: 2, value: 'Geek' }, { key: 3, value: 'neveropen' }, { key: 4, value: 'JavaScript' }, { key: 5, value: 'Course' } ]
Example 2: Creating the arrays of objects and adding them to another array.
Javascript
<script> const array1 = [ { key : 1 , value : "hello" } , { key : 2 , value : "Geek" } , { key : 3 , value : "neveropen" } , { key : 4 , value : "JavaScript" } , { key : 5 , value : "Course" } ]; const array2 = [ { key : 11 , value : "Courses" } , { key : 12 , value : "C++" } , { key : 13 , value : "JAVA" } , { key : 14 , value : "C" }, { key : 15 , value : "Many more" } ]; const array = [ array1 , array2 ]; console.log(array); </script> |
Output:
[ [ { key: 1, value: 'hello' }, { key: 2, value: 'Geek' }, { key: 3, value: 'neveropen' }, { key: 4, value: 'JavaScript' }, { key: 5, value: 'Course' } ], [ { key: 11, value: 'Courses' }, { key: 12, value: 'C++' }, { key: 13, value: 'JAVA' }, { key: 14, value: 'C' }, { key: 15, value: 'Many more' } ] ]
Here we have created two arrays containing various objects and then added these sub-arrays of objects to a base array or parent array.
Example 3: Printing the values of the nested array containing objects.
Javascript
<script> const array1 = [ { key : 1 , value : "hello" } , { key : 2 , value : "Geek" } , { key : 3 , value : "neveropen" } , { key : 4 , value : "JavaScript" } , { key : 5 , value : "Course" } ]; const array2 = [ { key : 11 , value : "Courses" } , { key : 12 , value : "C++" } , { key : 13 , value : "JAVA" } , { key : 14 , value : "C" }, { key : 15 , value : "Many more" } ]; const array = [ array1 , array2 ]; for ( let x = 0 ; x < array.length ; x++ ) { for ( let y = 0 ; y < array[0].length ; y++) { console.log( array[x][y].value ); } } </script> |
Output:
hello Geek neveropen JavaScript Course Courses C++ JAVA C Many more