Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-26 01:30:02
Original
1013 people have browsed it

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;
Copy after login

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"
    }
};
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template