In JavaScript, objects can contain other objects, which we call nested objects. This allows us to organize our data in a structured way and access nested data easily. In this tutorial, we will learn how to work with nested objects in Node.js.
Creating Nested Objects:
To create a nested object, you can define an object within another object like this:
const person = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "New York",
zipcode: "10001"
}
};
Now, person
is a nested object that contains an address
object.
Accessing Nested Properties:
You can access nested properties using dot notation like this:
console.log(person.name); // Output: John
console.log(person.address.city); // Output: New York
You can also use square brackets to access nested properties:
console.log(person["name"]); // Output: John
console.log(person["address"]["zipcode"]); // Output: 10001
Updating Nested Properties:
To update nested properties, you can simply assign a new value to the property like this:
person.name = "Jane";
person.address.city = "Los Angeles";
console.log(person.name); // Output: Jane
console.log(person.address.city); // Output: Los Angeles
Adding Nested Properties:
You can add new nested properties by assigning a value to a new property like this:
person.job = {
title: "Developer",
company: "ABC Inc"
};
console.log(person.job.title); // Output: Developer
console.log(person.job.company); // Output: ABC Inc
Nested Object Methods:
You can also define methods within nested objects. For example:
const person = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "New York",
getFullAddress: function() {
return `${this.street}, ${this.city}`;
}
}
};
console.log(person.address.getFullAddress()); // Output: 123 Main St, New York
Iterating Over Nested Objects:
You can loop over nested objects using for...in
loop like this:
for (let key in person) {
if (typeof person[key] === 'object') {
for (let nestedKey in person[key]) {
console.log(`${nestedKey}: ${person[key][nestedKey]}`);
}
} else {
console.log(`${key}: ${person[key]}`);
}
}
This will output all nested properties along with their values.
Conclusion:
Working with nested objects in Node.js allows you to organize your data in a structured way and access nested data easily. By following the steps in this tutorial, you should now have a good understanding of how to work with nested objects in Node.js.
⭐Check out UltraEdit – https://calcur.tech/Ultraedit
Node.js YouTube Playlist – https://calcur.tech/nodejs
Thank you so much!