Home  >  Article  >  Web Front-end  >  How to Access the Parent Object of a Nested Object in JavaScript?

How to Access the Parent Object of a Nested Object in JavaScript?

DDD
DDDOriginal
2024-10-26 01:30:02937browse

How to Access the Parent Object of a Nested Object in JavaScript?

How to Get the Parent Object of a Nested Object in JavaScript

In JavaScript, nested objects are commonly used to organize data in a hierarchical fashion. However, retrieving the parent object of a nested child object can be a bit tricky.

Consider the following example:

const obj = { subObj: { foo: 'hello world' } };

const s = obj.subObj;

The variable s now references the subObj object. Is it possible to obtain a reference to the obj object (the parent) from s?

No, a nested object does not have direct access to its parent.

This concept can be illustrated using another example:

const main = {
    name: "main object",
    child: {
        name: "child object"
    }
};

While main can access child.name, child cannot access main.name or any other properties of main.

Solution Using a Function

To overcome this limitation, a custom function can be used to initialize the child object with a reference to its parent:

const main = {
    name: "main object",
    child: {
        name: "child object"
    },
    init() {
        this.child.parent = this;
        delete this.init;
        return this;
    }
}.init();

Now, main.child.parent.name provides access to the main object's name property.

The above is the detailed content of How to Access the Parent Object of a Nested Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn