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...
- Use an
init
function to loop through at the time the nested object is created, or...
- Supply the nested object to a function that fills out the parent property
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 is set
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. The parenter
responsibilities are to recognize when an object is being set and then to...
Create a dummy proxy with the appropriate parent
and the parenter
handler
var p = new Proxy({parent: target}, parenter);
Copy 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 level
for(key in value){
p[key] = value[key];
}
Set the proxy not the supplied object
return target[prop] = p;
Full code
var parenter = {
set: function(target, prop, value){
if(typeof value === "object"){
var p = new Proxy({parent: target}, parenter);
for(key in value){
p[key] = value[key];
}
return target[prop] = p;
}else{
target[prop] = value;
}
}
}
var root = new Proxy({}, parenter);
root.child1 = {
color: "red",
value: 10,
otherObj: {
otherColor: "blue",
otherValue: 20
}
}
console.log(root.child1.color)
console.log(root.child1.otherObj.parent.color)
root.child2 = {color: "green", value3: 50};
console.log(root.child2.parent.child1.color)
root.child1.color = "yellow"
console.log(root.child2.parent.child1.color)
Notice that all root children always have parent properties, even children that are added later.
obj.subObj
is just a reference of the Object. If it were possible to get the "parent" of the Object, it would be a mess, simply because there can be multiple pointers pointing to the same Object and it will return multiple parents. – Derek 朕會功夫var my_string = "asdf"; my_string instanceof String; /* false */ my_string.constructor === String /* true */
. Can you explain? – Ryan Wheale