This question already has an answer here:
- access parent object in javascript 10 answers
I have the following (nested) object:
obj: { subObj: { foo: 'hello world' } };
Next thing I do is to reference the subobject like this:
var s = obj.subObj;
Now what I would like to do is to get a reference to the object obj
out of the variable s
.
Something like:
var o = s.parent;
Is this somehow possible?
You could try this(this uses a constructor, but I'm sure you can change it around a bit):
To further iterate on Mik's answer, you could also recursivey attach a parent to all nested objects.
http://jsbin.com/zupepelaciya/1/watch?js,console
No. There is no way of knowing which object it came from.
s
andobj.subObj
both simply have references to the same object.You could also do:
You now have three references,
obj.subObj
,obj2.subObj
, ands
, to the same object. None of them is special.Many of the answers here involve looping through an object and "manually" (albeit programmatically) creating a parent property that stores the reference to the parent. The two ways of implementing this seem to be...
init
function to loop through at the time the nested object is created, or...Both approaches have the same issue...
How do you maintain parents as the nested object grows/changes??
If I add a new sub-sub-object, how does it get its parent property filled? If you're (1) using an
init
function, the initialization is already done and over, so you'd have to (2) pass the object through a function to search for new children and add the appropriate parent property.Using ES6 Proxy to add
parent
whenever an object/sub-object isset
The approach below is to create a handler for a proxy always adds a parent property each time an object is set. I've called this handler the
parenter
handler. Theparenter
responsibilities are to recognize when an object is being set and then to...Create a dummy proxy with the appropriate
parent
and theparenter
handlerCopy in the supplied objects properties-- Because you're setting the proxy properties in this loop the
parenter
handler is working recursively; nested objects are given parents at each levelSet the proxy not the supplied object
Full code
Notice that all root children always have parent properties, even children that are added later.
when I load in a json object I usually setup the relationships by iterating through the object arrays like this:
then you can access the parent object of some object in the somechildarray by using .parent
Try this until a non-no answer appears: