How to use classes In Javascript
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' } }
How to Create a Nested Object in JavaScript ?
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:
Table of Content
- Using object literals
- Using square bracket notations
- Using factory function
- Using Object.create() method
- Using object constructor
- Using JavaScript classes