Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a "nested" object constructor in JavaScript?

Tags:

People also ask

What is nested object in JavaScript?

The basic definition of an object in JavaScript is a container for named values called properties (keys). Sometimes, we need to create an object inside another object. In this case, it's called a nested object.

How do I create a nested object in JavaScript?

const obj = { code: "AA", sub: { code: "BB", sub: { code: "CC", sub: { code: "DD", sub: { code: "EE", sub: {} } } } } }; Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple. We can solve this problem using a recursive approach.

How do you define nested objects?

Nested objects are the objects that are inside an another object. In the following example 'vehicles' is a object which is inside a main object called 'person'. Using dot notation the nested objects' property(car) is accessed.


Is it possible to define an object within another object? I'm thinking something like this:

function MyObj(name) {
    this.name = name;

    function EmbeddedObj(id) {
        this.id = id;
    }
}

And I could then create an EmbeddedObj like this:

var myEmbeddedObj = new MyObj.EmbeddedObj();

Meme for bonus points: Objectception! :o