How to Create a Nested Object in JavaScript ?
Last Updated :
17 Jan, 2024
JavaScript allows us to create objects having the properties of the other objects this process is called as nesting of objects. Nesting helps in handling complex data in a much more structured and organized manner by creating a hierarchical structure.
These are the different methods to create nested objects in JavaScript are as follows:
Using object literals
JavaScript allows us to create and define the objects using curly braces { } which are called object literals. These objects' literals have key-value pairs where identifiers or strings are the keys and the value can be of any data type be it object, string, number, etc.
Example: This example shows creating nested objects using object literals.
JavaScript
let object = {
Company:
{
name: "GeeksforGeeks",
location: "Noida",
Domains:
{
Courses: ["DSA Self Paced Course",
"Full Stack Development",
"Devops Boot Camp",
"GATE Prepration"],
Articles: [
`Interview Prepration, Algorithms,
Data Structures, Web Development`]
}
},
}
console.log(object);
Output{
Company: {
name: 'GeeksforGeeks',
location: 'Noida',
Domains: { Courses: [Array], Articles: [Array] }
}
}
Using square bracket notations
Square brackets are used in JavaScript primarily for accessing arrays but they can also be used for accessing or for creating nested objects in JavaScript. Here is an explanation for creating and then accessing nested objects in java script.
Example: This example shows creating nested objects using square brackets notations.
JavaScript
// Declare and initialize the keys
let OuterObj = {};
const firstKey = 'key01';
const secondKey = 'key02';
const nestedFirstKey = 'nestedKey01';
const nestedSecondKey = 'nestedKey02';
// Assign values to the keys
OuterObj[firstKey] = 'First Key Value';
OuterObj[secondKey] = {};
OuterObj[secondKey][nestedFirstKey] = 'First Nested Value';
OuterObj[secondKey][nestedSecondKey] = 'Second Nested Value';
// Output
console.log(OuterObj);
Output{
key01: 'First Key Value',
key02: {
nestedKey01: 'First Nested Value',
nestedKey02: 'Second Nested Value'
}
}
Using factory function
We can also create nested objects in javaScript by using factory function so as to define the objects and their organised nested structure.
Example: This example shows creating nested objects using factory function.
JavaScript
function objects() {
let nestedObjects = {
obj: {
Company:
{
name: "GeeksforGeeks"
}
}
}
return nestedObjects;
}
console.log(objects());
Output{ obj: { Company: { name: 'GeeksforGeeks' } } }
JavaScript provide us the Object.create() method for creating nested objects allowing us to create new object from an already existing objects, below is an example explaining the creation of nested objects using Object.create() method.
Example: This example shows the creating nested objects using Object.create() method.
JavaScript
// Define the parent object
const parentObject = {
firstProperty: 'GeeksforGeeks',
secondProperty: 'A Computer Science Portal',
};
// Creating a child object
// with parentObject as its prototype
const childObject = Object.create(parentObject);
// Adding properties to the child object
childObject.thirdProperty = 'Noida';
//Output parent object and child object
console.log('Parent Object:', parentObject);
console.log('Child Object:', childObject);
OutputParent Object: {
firstProperty: 'GeeksforGeeks',
secondProperty: 'A Computer Science Portal'
}
Child Object: { thirdProperty: 'Noida' }
Using object constructor
JavaScript allows us to create the nested objects using constructor function which work as the initial starting point for the creation of the objects with the specific properties and behaviour. It can be used defining the each level of the nested objects hierarchy.
Example: This example shows the creating nested Object using object constructor.
JavaScript
function company(name, location, courseObj) {
this.name = name;
this.location = location;
this.course = courses;
}
function course(courseName) {
this.courseName = courseName;
}
let courses = new course("DSA self paced course")
let companyName = new company("GeekforGeeks",
"Noida", courses);
console.log(companyName);
Outputcompany {
name: 'GeekforGeeks',
location: 'Noida',
course: course { courseName: 'DSA self paced course' }
}
Using JavaScript classes
This approach provide a more structured way for creating nested objects by using ES6 class syntax to instantiate the objects and their structure. Here each class can be used for instantiating the each level of the hierarchy of code.
Example: This example shows the creating nested object using JavaScript ES 6 classes.
JavaScript
class Details {
constructor(name, location) {
this.name = name;
this.location = location;
}
}
class Company {
constructor(courses) {
this.courses = courses;
}
}
let cpyDetails = new Company("DSA Self Paced Course");
let companyDets = new Details("GeekforGeeks", "Noida");
companyDets.company = cpyDetails;
console.log(companyDets);
OutputDetails {
name: 'GeekforGeeks',
location: 'Noida',
company: Company { courses: 'DSA Self Paced Course' }
}
Similar Reads
How to Extend an Object in JavaScript ?
Extending an object in JavaScript means adding properties or methods to enhance its functionality. This can be done dynamically. The extends keyword is used to create a subclass from a parent class, enhancing object-oriented programming flexibility in JavaScript. Syntax:class childclass extends pare
2 min read
Object.create vs. New in JavaScript
The new keyword and Object.create() are frequently used to instantiate objects in JavaScript but they have distinct characteristics and use cases. Understanding the differences between new and Object.create() is essential for mastering object creation in JavaScript. What is new?The new keyword in Ja
2 min read
How to Deep-Freeze an Object in JavaScript?
In JavaScript, freezing an object prevents it from being modified. This means you can no longer add, remove, or modify the properties of an object. However, by default, JavaScript's Object.freeze() only freezes the top level of an object, leaving nested objects or arrays mutable. To achieve immutabi
4 min read
How to create object properties in JavaScript ?
JavaScript is built on an object-oriented framework. An object is a collection of properties, where each property links a key to a value. These properties are not in any specific order. The value of a JavaScript property can be a method (function). Object properties can be updated, modified, added,
4 min read
How to Deep Merge Two Objects in JavaScript ?
Typically, in JavaScript, combining two objects is a commonplace thing to do, but when it involves intricate nesting, deep merging turns out to be necessary, deep merge is the activity of taking the attributes or features from multiple objects (which have nested objects) and creating a new object wi
3 min read
How to Clone a JavaScript Object?
Here are different methods to clone a JavaScript object.1. Using Object.assign() MethodThe Object.assign() method is used to clone the given object. We have assigned the given object to the new empty object by just using this method. Syntaxlet Clone_object =Object.assign({}, sourceObject);Note: This
2 min read
How to create an object with prototype in JavaScript ?
In this article, we will discuss object creation & prototypes, along with understanding the different ways for object creation & their implementation through the examples. Prototypes are the mechanism by which objects in JavaScript inherit features from another object. A prototype property i
4 min read
JavaScript Object create() Method
JavaScript object.create() method is used to create a new object with the specified prototype object and properties. Object.create() method returns a new object with the specified prototype object and properties.Syntax:Object.create(prototype[, propertiesObject])Parameters:prototype: It is the proto
3 min read
How to Convert Object to Array in JavaScript?
In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
4 min read
How to Create JSON String in JavaScript?
JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication. Below are the following approaches to creating a JSON string: Table of Conte
2 min read