JavaScript Nested Object
Objects are basic data structures in JavaScript that serve as containers for sets of methods and properties. Values might be simple data kinds like texts or numbers, but more significantly, they can also be other objects that are stored in properties. Nestled objects are produced via this capability, in which an item’s attribute holds another object. You can create increasingly intricate constructions by nesting things inside of one another. They can go “very many levels deep” if necessary.
Because they give you more freedom in your code and allow you to represent more complex relationships and structures seen in abstract notions or real life settings, nested objects are very helpful. Related properties can be grouped within their own sub-object rather than being a flat list of named properties.
Object literals are collections of key value pairs encased in curly braces {} that can be used to create nested objects. Another object literal can serve as the value linked to a key (the property name).
An example representation of a business with an address. It makes reasonable to express the address as a separate object nested inside the firm object because an address is made up of several different elements (street, city, zip code, and state).
// Creating a nested object using object literals
let company = {
companyName: “Healthy Candy”, // A simple string property
activity: “food manufacturing”, // Another simple string property
// The ‘address’ property holds a nested object
address: {
street: “2nd street”,
number: “123”,
zipcode: “33116”,
city: “Miami”,
state: “Florida”
},
yearOfEstablishment: 2021 // Another simple number property
}; console.log(company);
The value of the address attribute in this company object is another object with its own properties (street, number, zipcode, city, state) rather than a straightforward string or integer.
You can use either dot notation (.) or square bracket notation ([]) to chain the property names in order to access properties within nested objects. To access the desired property, you begin with the outer object’s name and work your way down through the nested objects.
// Define the company object with nested properties
const company = {
name: “Tech Solutions Inc.”,
address: {
street: “2nd street”,
city: “Miami”,
zipcode: “33116”
},
phone: “555-1234”
};
// Accessing nested properties using dot notation
console.log(“Company City:”, company.address.city);
// Accessing nested properties using square bracket notation
console.log(“Company Zipcode:”, company[“address”][“zipcode”]);
// Mixing notation
console.log(“Company Street:”, company.address[“street”]);
JavaScript objects can have their properties changed after they are created because they are changeable. Likewise, this holds true for nested properties. By accessing a nested property using the chained notation and assigning a new value, you can change its value:
// Define the ‘company’ object with nested properties
let company = {
name: “Tech Solutions Inc.”,
address: {
street: “123 Main St”,
city: “Miami”,
state: “FL”,
zipcode: “33101”,
number: “50” // Initial number property
},
departments: [
{ name: “Sales”, employees: 20 },
{ name: “Engineering”, employees: 50 }
]
};
console.log(“Original Zipcode:”, company.address.zipcode);
console.log(“Original Number:”, company.address.number);
console.log(“————————————“);
// Modifying a nested property using dot notation
company.address.zipcode = “33117”;
console.log(“Updated Zipcode (dot notation):”, company.address.zipcode);
// Modifying a nested property using bracket notation
company[“address”][“number”] = “100”;
console.log(“Updated Number (bracket notation):”, company.address.number);
console.log(“————————————“);
console.log(“Final company object state:”);
console.log(company);
By giving a value to a property name that doesn’t exist on the nested object, you can also add new properties to it in the same manner as you can add properties to any other object.
Nestled objects can also have methods, which are functions saved as object properties.
const company = {
name: “Tech Solutions Inc.”,
address: {
number: “100”,
street: “2nd street”,
city: “Miami”,
state: “Florida”,
zipcode: “33117”,
getFullAddress: function() {
return `${this.number} ${this.street}, ${this.city}, ${this.state} ${this.zipcode}`;
}
}
};
// Calling the nested method
console.log(“Full Address:”, company.address.getFullAddress());
// Expected Output: Full Address: 100 2nd street, Miami, Florida 33117
As suggested by this behaviour and the prior discussion, this refers to the address object itself inside the getFullAddress function, giving it access to its own properties like number, street, etc.
By stacking arrays within arrays, objects within arrays, and mixing these patterns, you can build even more intricate structures than merely objects within objects. For instance, an array of address objects inside the company object could be used to represent a corporation’s many addresses.
// Company object with an array of address objects
let company = {
companyName: “Healthy Candy”,
activities: [“food manufacturing”, “improving kids’ health”, “manufacturing toys”], // Array in an object
address: [{ // Array of objects in an object
street: “2nd street”,
number: “123”,
zipcode: “33116”,
city: “Miami”,
state: “Florida”
}, {
street: “1st West avenue”,
number: “5”,
zipcode: “75001”,
city: “Addison”,
state: “Texas”
}],
yearOfEstablishment: 2021
};
// Accessing a property in an object within an array within an object
console.log(“Second Address City:”, company.address.city);
// Outputs: Second Address City: Addison
Because arrays have indexed attributes rather than named ones, they are regarded as a unique kind of object in JavaScript. This indicates that extremely flexible and complex data representations are made possible by the combination of objects and arrays.
The Document Object Model (DOM), which depicts an HTML document as a tree structure of nested objects (nodes), is a well-known real-world example of nested objects. Usually, the window object is nested inside the document object. An object hierarchy is created when HTML components like <body> contain other elements like <div>, which in turn contain elements like <p>. Chaining object and property accessors allows you to work with this structure. For example, window.document.forms allows you to access the first form element. This type of nesting is also commonly used in JSON formats.
This important feature in JavaScript allows the generation and manipulation of large, hierarchical data structures, which are vital for constructing realistic and sophisticated applications.