How to create an array with multiple objects having multiple nested key-value pairs in JavaScript?


JavaScript is a versatile language that is widely used for creating dynamic web applications. One of the most common data structures used in JavaScript is the array. An array is a collection of elements that can be of any type, including objects. In this article, we will discuss how to create an array with multiple objects having multiple nested key-value pairs in JavaScript.

What are arrays?

An array is a special type of object that stores a collection of values. These values can be of any data type, such as numbers, strings, booleans, and even other arrays. Arrays are a very powerful feature in JavaScript and are used in many different kinds of applications.

Syntax

let myArray = [20, 22, 24];
Or
const arr = [hello, ‘world’];

Creating an Array with Multiple Objects

Firstly, to create an array with multiple objects in JavaScript, we have to define an empty array, and to do that we can use the [] notation. After defining the array, we can use the push() method to add objects or multiple objects in the array. For example −

let arr = [];
arr.push({
  key1: value1,
  key2: value2
});
arr.push({
  key1: value3,
  key2: value4
});

In the given example, we have denied an array called "arr" that has two objects. We have used the push() method to add each object to the end of the array. Array objects here are defined using curly braces {} having key-value pairs. Once we have created the array with the objects, it is now available to access and manipulate the objects & their properties using JavaScript methods or operations.

There are multiple ways to access the objects in the array, one way is to loop through the array using forEach method() and access each object and its properties separately, or we may also use methods like map() or filter() for transforming or manipulating the elements in the array.

Adding Nested Key-Value Pairs to Objects

After creating the array, we can now add nested key-value pairs to objects by defining an object within another object. For instance −

let myObj = {
  key1: value1,
  key2: {
    nestedKey1: nestedValue1,
    nestedKey2: nestedValue2
  }
};

In the given example, we defined myObj as object with two key-value pairs. The value of the key2 pair is another object with two nested key-value pairs.

Creating an Array with Objects with Nested Key-Value Pairs

To create an array with objects having nested key-value pairs, we can combine the techniques discussed above. For example −

let arr = [];
arr.push({
  key1: value1,
  key2: {
    nestedKey1: nestedValue1,
    nestedKey2: nestedValue2
  }
});
arr.push({
  key1: value3,
  key2: {
    nestedKey1: nestedValue3,
    nestedKey2: nestedValue4
  }
});

Above, we have defined an empty array arr, and added two objects to it using the push() method where each object contains two key-value pairs, with the value of key2 being another object with two nested key-value pairs.

Accessing data in an array of objects with nested key-value pairs

Approach 1

In this approach, we will be accessing the data in an array of objects with nested key-value pairs using a combination of dot notation and bracket notation. Dot notation allows accessing the properties of an object directly whereas in bracket notation, we can access the properties using a variable.

As an example, we can access the name property of the first object in arr, using dot notation like below −

const objOne = arr[0];
const object = objOne.name;

Here, we have assigned the first object in arr to a variable called objOne. Now using the dot notation, we can access any property of objOne and assign it to a variable called object.

For accessing the state property of the address property of the second object in arr, we may use the bracket notation like below −

const objTwo = arr[1];
const address = objTwo["city"]["state"];

Here, we have assigned another object in arr to a variable called objTwo. Now using the bracket notation, we can access the city property of objTwo, after which the state property of the nested object to assign to the address variable.

Approach 2

Another way to access data in an array of objects with nested key-value pairs can be done using the forEach() method. In this method, the arrays are iterated over using the forEach() method and for each object within the array, a for...in loop is used to extract the value of each key-value pair. The values are then pushed into a new array.

Example 1

The example displays the creation of an array with multiple objects having nested key-value pairs.

We have created an empty array called arr and used the push() method to add three objects to it. Each object has a key-value pair: key1 with a value of "value1", key2 with a value of "value2", and so on. The push() method adds items to an array and takes one or more arguments that represent the items to add, and finally, the three objects are passed in as separate arguments.

<!DOCTYPE html>
<html>
   <body>
      <p id="array"></p>
      <script>
         let arr = [];
         arr.push({ key1: "value1" }, { key2: "value2" }, { key3: "value 3" });
         document.getElementById("array").innerHTML = JSON.stringify(arr);
      </script>
   </body>
</html>

Example 2

The example displays the creation of two arrays with multiple objects having nested key-value pairs and adding them into one array.

In this below code, we loop through each object in arr1 and arr2 using a for...in loop to access the values associated with each key. We then push only the values into the arr3 array using arr3.push(object[key]).

<!DOCTYPE html>
<html>
   <body>
      <p id="array"></p>
      <script>
         const arr1 = [
            { key1: "value 1" },
            { key2: "value 2" },
            { key3: "value 3" },
         ];
         const arr2 = [
            { key4: "value 4" },
            { key5: "value 5" },
            { key6: "value 6" },
         ];
         const arr3 = [];
         arr1.forEach(function (object) {
            for (const key in object) {
               arr3.push(object[key]);
            }
         });
         arr2.forEach(function (object) {
            for (const key in object) {
               arr3.push(object[key]);
            }
         });
         document.getElementById("array").innerHTML = JSON.stringify(arr3);
      </script>
   </body>
</html>

Conclusion

Arrays are an important data structure in JavaScript that can store a collection of information of any data type, including objects. Creating an array with multiple objects having multiple nested key-value pairs is a simple process, to do this we first define an empty array & add objects to it using the push() method, where each object is defined using {} (curly braces), containing key-value pairs separated using commas. To access, and manipulate the objects and their properties, we can use JavaScript methods.

We can also add nested key-value pairs to objects by defining an object within another object. The method of using objects with nested key-value pairs can create more powerful and flexible data structures in JavaScript. We saw different ways including a combination of dot notation and bracket notation or using the forEach() method and a for...in loop to extract the value of each key-value pair, to access the data in an array of objects with nested key-value pairs.

Updated on: 13-Apr-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements