2

I have the following code in javascript :

var x = {
    a:1,
    b : {
        c : 2,
        d : //i want value of x.a in here  
    }
}

I have read that accessing parent property like this is not at all possible. Is there any workaround for this?

2
  • The nested object could be part of multiple other objects, hence there is no single parent. Commented Dec 30, 2014 at 9:47
  • You might want to use something like: jsfiddle.net/34cooh91 or something like this: jsfiddle.net/34cooh91/1 Commented Dec 30, 2014 at 10:10

5 Answers 5

2

No, there isn't. Nested objects don't have access to their hosts as in any other language as well.

You have to set the explicitly by yourself.

Sign up to request clarification or add additional context in comments.

Comments

0

No, it's not possible, but your case can be written like:

var x = new function(){
   this.a = 1;
   this.b = {
      c: 2,
      d: this.a
   }
};

2 Comments

This isn't the same. Check the console for this: x.a = 5; console.log(x.b);
@abhitalks of course it's not change, because a storing primitive type
0

A javascript object doesn't have a parent because you can have sharing. For example:

var a = { x: 42 };
var b = { y: a };
var c = { z: a };

here the object a is "shared" as sub-object between b and c, so what should be the "parent" or a? You can see the sharing because after executing b.y.x = 99, also c.z.x will show be 99. A single javascript object may be reachable using different paths.

DOM objects on the other hand have a parent because the DOM is a tree structure and it makes sense to talk about "the" parent of a node.

If you add a DOM node as a child of another and the node is already part of the DOM it will be removed from where it is and it will be placed in the new position.

Comments

0

The parent reference does not exist in javascript. What you can do is build an helper recursive function that will parse all your object and add a reference to the parent. This will build a more complex object.

Here is a video which shows how to : http://blog.wax-o.com/2014/01/how-to-find-deep-and-get-parent-in-javascript-nested-objects-with-recursive-functions-and-the-reference-concept-level-beginner/

Comments

0

try this:

var x = {
          a: {
               c: 1
          },
          b: {
               c: 2  
          }
}

x['b']['d'] = x['a'];

should work ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.