1

I've been searching a way to get the Parent object property in a nested Object but had no luck.

Here is the nested object I am using:

var obj = {
        name: 'My Name',
        obj1: {
                 age: 18,
                 name: this.name
            }
    };

But it gives and undefined error.

Is there any way in JavaScript or jQuery to achieve it?

2 Answers 2

4

You can do something like this :

var obj = new obj();

function obj(){
    var self = this;
    self.name = 'My Name';
    self.obj1 = {
        age: 18,
        name: self.name
    }
};
Sign up to request clarification or add additional context in comments.

Comments

0

And with some jQuery love, I achieved it.

Here is the original one I was using:

var obj = {
        name: 'My Name',
        obj1: {
                 age: 18,
                 name: this.name
            }
    };

And here is my trick:

I created another object obj1Copy:

var obj1Copy = {
    name: obj.name
};

See I am using the parent object name instead of this in this copy. And then use the jQuery $.extend to merge them:

var newObj = $.extend(obj.obj1, obj1Copy);

And then use the newObj instead of obj1, like newObj.name would return My Name.

If there's any better and easy way then please share.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.