Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
To create an array with multiple objects in JavaScript, we can define an empty array using the [] notation. After defining the array, we can use the push() method to add objects to the array:
let arr = [];
arr.push({
key1: "value1",
key2: "value2"
});
arr.push({
key1: "value3",
key2: "value4"
});
console.log(arr);
[
{ key1: 'value1', key2: 'value2' },
{ key1: 'value3', key2: 'value4' }
]
In the example above, we have defined an array called "arr" that has two objects. We used the push() method to add each object to the end of the array. Array objects are defined using curly braces {} with key-value pairs separated by commas.
Adding Nested Key-Value Pairs to Objects
We can add nested key-value pairs to objects by defining an object within another object:
let myObj = {
key1: "value1",
key2: {
nestedKey1: "nestedValue1",
nestedKey2: "nestedValue2"
}
};
console.log(myObj);
{
key1: 'value1',
key2: { nestedKey1: 'nestedValue1', nestedKey2: 'nestedValue2' }
}
In this example, myObj has two key-value pairs where the value of key2 is another object with two nested key-value pairs.
Creating an Array with Objects Having Nested Key-Value Pairs
To create an array with objects having nested key-value pairs, we combine the techniques discussed above:
let students = [];
students.push({
name: "Alice",
age: 20,
address: {
street: "123 Main St",
city: "New York",
country: "USA"
},
grades: {
math: 95,
science: 88
}
});
students.push({
name: "Bob",
age: 22,
address: {
street: "456 Oak Ave",
city: "Los Angeles",
country: "USA"
},
grades: {
math: 78,
science: 92
}
});
console.log(students);
[
{
name: 'Alice',
age: 20,
address: { street: '123 Main St', city: 'New York', country: 'USA' },
grades: { math: 95, science: 88 }
},
{
name: 'Bob',
age: 22,
address: { street: '456 Oak Ave', city: 'Los Angeles', country: 'USA' },
grades: { math: 78, science: 92 }
}
]
Accessing Data in Nested Objects
Using Dot Notation
We can access nested properties using dot notation by chaining the property names:
// Access the first student's name console.log(students[0].name); // Access nested address information console.log(students[0].address.city); // Access nested grades console.log(students[1].grades.math);
Alice New York 78
Using Bracket Notation
Bracket notation is useful when property names are stored in variables or contain special characters:
let property = "address"; let nestedProperty = "country"; console.log(students[0][property][nestedProperty]); // Also works with regular property access console.log(students[1]["name"]);
USA Bob
Using forEach() Method
We can iterate through the array and access nested properties for each object:
students.forEach((student, index) => {
console.log(`Student ${index + 1}:`);
console.log(`Name: ${student.name}`);
console.log(`City: ${student.address.city}`);
console.log(`Math Grade: ${student.grades.math}`);
console.log("---");
});
Student 1: Name: Alice City: New York Math Grade: 95 --- Student 2: Name: Bob City: Los Angeles Math Grade: 78 ---
Direct Array Creation
Instead of using push(), we can create the entire array with nested objects directly:
const employees = [
{
id: 1,
name: "John Doe",
department: {
name: "Engineering",
location: "Building A"
},
skills: {
primary: "JavaScript",
secondary: "Python"
}
},
{
id: 2,
name: "Jane Smith",
department: {
name: "Marketing",
location: "Building B"
},
skills: {
primary: "SEO",
secondary: "Content Writing"
}
}
];
console.log(employees[0].department.name);
console.log(employees[1].skills.primary);
Engineering SEO
Conclusion
Creating arrays with multiple objects having nested key-value pairs is a powerful way to structure complex data in JavaScript. Use dot notation for simple access, bracket notation for dynamic properties, and methods like forEach() to iterate through and manipulate the data efficiently.
