Open In App

How to Create a Nested Object in JavaScript ?

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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' } } }

Using Object.create() method

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);


Output

Parent 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);


Output

company {
  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);


Output

Details {
  name: 'GeekforGeeks',
  location: 'Noida',
  company: Company { courses: 'DSA Self Paced Course' }
}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads