Understanding Nested Objects in JavaScript
Irena Popova 👩🏻💻
Posted on October 25, 2024
Objects are what you are dealing with working as a JavaScript developer, and needless to say, that holds true for TypeScript as well. TypeScript provides you with multiple ways to define type definitions for object properties. We'll look at a couple of them throughout this post, starting with simple examples and moving on to some advanced type definitions.
Nested objects in JavaScript are objects that contain other objects or arrays as their properties. This allows for the creation of complex data structures that can represent real-world entities more effectively.
In JavaScript, you can nest objects within other objects. This is also known as object nesting or object composition. Object nesting allows you to create complex data structures by organizing objects within objects.
Creating a Nested Object
Here's a simple example of a nested object representing a user profile:
const userProfile = {
username: "irena_doe",
age: 30,
contact: {
email: "irena@example.com",
phone: {
home: "123-456-7890",
mobile: "987-654-3210"
}
},
preferences: {
notifications: true,
theme: "dark"
}
};
For example:
The userProfile
object has properties like username, age, and contact.
The contact property itself is an object containing email and phone.
The phone property is another nested object with home and mobile numbers.
Accessing Nested Object Properties
To access properties within nested objects, you can use dot notation or bracket notation. Here’s how you can access the user's mobile phone number:
const mobileNumber = userProfile.contact.phone.mobile;
console.log(mobileNumber); // Output: 987-654-3210
You can also modify nested properties. For example, if you want to change the theme preference:
userProfile.preferences.theme = "light";
console.log(userProfile.preferences.theme); // Output: light
Using Types with Nested Objects
When working with TypeScript, you can define types for nested objects to ensure type safety. Here’s how you can define a type for the userProfile object:
type UserProfile = {
username: string;
age: number;
contact: {
email: string;
phone: {
home: string;
mobile: string;
};
};
preferences: {
notifications: boolean;
theme: string;
};
};
const user: UserProfile = {
username: "irena_doe",
age: 30,
contact: {
email: "irena@example.com",
phone: {
home: "123-456-7890",
mobile: "987-654-3210"
}
},
preferences: {
notifications: true,
theme: "dark"
}
};
In this TypeScript example, the UserProfile
type defines the structure of the userProfile
object, ensuring that all properties are correctly typed.
Here is another example of Nested Objects in JavaScript
Let’s look at a more complex example that represents a library system, where each book has various details, including its author, publisher, and genres.
Nested objects can be defined using the type keyword itself. TypeScript can also abstract away the type definitions of a nested object into type definitions. Index signatures can be used when you are unsure of how many properties an object will have but you are sure of the type of properties of an object
Defining a Nested Object for a Library System
Here’s how you can structure a nested object for this scenario:
const library = {
name: "Central City Library",
location: {
address: {
street: "123 Main St",
city: "Central City",
state: "CC",
zip: "12345"
},
coordinates: {
latitude: 40.7128,
longitude: -74.0060
}
},
books: [
{
title: "JavaScript: The Good Parts",
author: {
firstName: "Douglas",
lastName: "Crockford"
},
publishedYear: 2008,
genres: ["Programming", "Technology"],
availableCopies: 5
},
{
title: "Clean Code",
author: {
firstName: "Robert",
lastName: "C. Martin"
},
publishedYear: 2008,
genres: ["Programming", "Software Engineering"],
availableCopies: 3
}
],
totalBooks: function() {
return this.books.length;
}
};
Let's breakdown of the Nested Object Structure
- Library Object: Represents the entire library and contains properties like name, location, and books.
- Location Object: Contains nested objects for address and coordinates.
- address includes street, city, state, and zip code. coordinates stores latitude and longitude.
- Books Array: An array that holds multiple book objects, each containing:
- Title: The title of the book.
- Author Object: Nested object that includes
firstName
andlastName
of the author.
-Published Year: The year the book was published.
-Genres: An array of genres that the book belongs to.
-Available Copies: A number indicating how many copies are available.
Accessing and Manipulating Data
You can access and manipulate this nested object in various ways. Here’s how to get the author of the first book:
const firstBookAuthor = library.books[0].author;
console.log(`${firstBookAuthor.firstName} ${firstBookAuthor.lastName}`);
// Output: Douglas Crockford
To add a new book to the library:
library.books.push({
title: "The Pragmatic Programmer",
author: {
firstName: "Andrew",
lastName: "Hunt"
},
publishedYear: 1999,
genres: ["Programming", "Career"],
availableCopies: 4
});
Using a Method in the Object
You can also utilize methods defined in the object. For example, to get the total number of books:
console.log(library.totalBooks()); // Output: 3
This example illustrates how nested objects can be used to create a more comprehensive structure to represent complex data, such as a library system. By organizing related information together, you can easily manage and interact with the data in a meaningful way.
Another nested example
To improve code organization and maintainability, you can abstract nested objects into separate types. This approach allows you to define a Caterer type separately and use it within the Train type. Here’s how you can do this in TypeScript:
// Define the type for Caterer
type Caterer = {
name: string; // Name of the catering company
address: string; // Address of the catering company
phone: number; // Phone number of the catering company
};
Defining the Train Type
Next, we will define the Train type, which will use the Caterer type for its caterer property.
// Define the type for Train
type Train = {
model: string; // Model of the train
trainNumber: string; // Unique train number
timeOfDeparture: Date; // Departure time
timeOfArrival: Date; // Arrival time
caterer: Caterer; // Reference to the Caterer type
};
Example of a Train Object
Now, we can create an instance of the Train type, including the Caterer details.
// Example of a Train object
const train: Train = {
model: "Shinkansen N700",
trainNumber: "S1234",
timeOfDeparture: new Date("2024-10-25T09:00:00Z"),
timeOfArrival: new Date("2024-10-25T11:30:00Z"),
caterer: {
name: "Gourmet Train Catering",
address: "123 Culinary Ave, Tokyo",
phone: 1234567890,
},
};
The benefits of this approach are:
- Reusability: The Caterer type can be reused in other parts of your code, such as in different transportation types (e.g., airplanes, buses).
- Clarity: Separating the Caterer type makes the Train type cleaner and easier to understand.
- Maintainability: If the structure of the Caterer changes, you only need to update it in one place.
By abstracting nested objects into separate types, you can enhance the organization and clarity of your TypeScript code. This approach allows for better reusability and maintainability, making it easier to manage complex data structures.
Let's recap
Nested objects are a powerful feature in JavaScript that allows for the organization of complex data structures.
By using nested objects, you can create more meaningful representations of data, making your code easier to understand and maintain. Additionally, using TypeScript can help enforce structure and type safety when dealing with these complex objects.
Posted on October 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.