Javascript objects: get parent [duplicate]
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 开发者_如何学Goreference to the object obj
out of the variable s
.
Something like:
var o = s.parent;
Is this somehow possible?
A nested object (child) inside another object (parent) cannot get data directly from its parent.
Have a look on this:
var main = {
name : "main object",
child : {
name : "child object"
}
};
If you ask the main object what its child name is (main.child.name
) you will get it.
Instead you cannot do it vice versa because the child doesn't know who its parent is.
(You can get main.name
but you won't get main.child.parent.name
).
By the way, a function could be useful to solve this clue.
Let's extend the code above:
var main = {
name : "main object",
child : {
name : "child object"
},
init : function() {
this.child.parent = this;
delete this.init;
return this;
}
}.init();
Inside the init
function you can get the parent object simply calling this
.
So we define the parent
property directly inside the child
object.
Then (optionally) we can remove the init
method.
Finally we give the main object back as output from the init
function.
If you try to get main.child.parent.name
now you will get it right.
It is a little bit tricky but it works fine.
No. There is no way of knowing which object it came from.
s
and obj.subObj
both simply have references to the same object.
You could also do:
var obj = { subObj: {foo: 'hello world'} };
var obj2 = {};
obj2.subObj = obj.subObj;
var s = obj.subObj;
You now have three references, obj.subObj
, obj2.subObj
, and s
, to the same object. None of them is special.
This is an old question but as I came across it looking for an answer I thought I will add my answer to this to help others as soon as they got the same problem.
I have a structure like this:
var structure = {
"root":{
"name":"Main Level",
nodes:{
"node1":{
"name":"Node 1"
},
"node2":{
"name":"Node 2"
},
"node3":{
"name":"Node 3"
}
}
}
}
Currently, by referencing one of the sub nodes I don't know how to get the parent node with it's name value "Main Level".
Now I introduce a recursive function that travels the structure and adds a parent attribute to each node object and fills it with its parent like so.
var setParent = function(o){
if(o.nodes != undefined){
for(n in o.nodes){
o.nodes[n].parent = o;
setParent(o.nodes[n]);
}
}
}
Then I just call that function and can now get the parent of the current node in this object tree.
setParent(structure.root);
If I now have a reference to the seconds sub node of root, I can just call.
var node2 = structure.root.nodes["node2"];
console.log(node2.parent.name);
and it will output "Main Level".
Hope this helps..
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 theparenter
handlervar 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 levelfor(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);
// some examples
root.child1 = {
color: "red",
value: 10,
otherObj: {
otherColor: "blue",
otherValue: 20
}
}
// parents exist/behave as expected
console.log(root.child1.color) // "red"
console.log(root.child1.otherObj.parent.color) // "red"
// new children automatically have correct parent
root.child2 = {color: "green", value3: 50};
console.log(root.child2.parent.child1.color) // "red"
// changes are detected throughout
root.child1.color = "yellow"
console.log(root.child2.parent.child1.color) // "yellow"
Notice that all root children always have parent properties, even children that are added later.
There is a more 'smooth' solution for this :)
var Foo = function(){
this.par = 3;
this.sub = new(function(t){ //using virtual function to create sub object and pass parent object via 't'
this.p = t;
this.subFunction = function(){
alert(this.p.par);
}
})(this);
}
var myObj = new Foo();
myObj.sub.subFunction() // will popup 3;
myObj.par = 5;
myObj.sub.subFunction() // will popup 5;
To further iterate on Mik's answer, you could also recursivey attach a parent to all nested objects.
var myApp = {
init: function() {
for (var i in this) {
if (typeof this[i] == 'object') {
this[i].init = this.init;
this[i].init();
this[i].parent = this;
}
}
return this;
},
obj1: {
obj2: {
notify: function() {
console.log(this.parent.parent.obj3.msg);
}
}
},
obj3: {
msg: 'Hello'
}
}.init();
myApp.obj1.obj2.notify();
http://jsbin.com/zupepelaciya/1/watch?js,console
You could try this(this uses a constructor, but I'm sure you can change it around a bit):
function Obj() {
this.subObj = {
// code
}
this.subObj.parent = this;
}
I have been working on a solution to finding the parent object of the current object for my own pet project. Adding a reference to the parent object within the current object creates a cyclic relationship between the two objects.
Consider -
var obj = {
innerObj: {},
setParent: function(){
this.innerObj.parent = this;
}
};
obj.setParent();
The variable obj will now look like this -
obj.innerObj.parent.innerObj.parent.innerObj...
This is not good. The only solution that I have found so far is to create a function which iterates over all the properties of the outermost Object until a match is found for the current Object and then that Object is returned.
Example -
var obj = {
innerObj: {
innerInnerObj: {}
}
};
var o = obj.innerObj.innerInnerObj,
found = false;
var getParent = function (currObj, parObj) {
for(var x in parObj){
if(parObj.hasOwnProperty(x)){
if(parObj[x] === currObj){
found = parObj;
}else if(typeof parObj[x] === 'object'){
getParent(currObj, parObj[x]);
}
}
}
return found;
};
var res = getParent(o, obj); // res = obj.innerObj
Of course, without knowing or having a reference to the outermost object, there is no way to do this. This is not a practical nor is it an efficient solution. I am going to continue to work on this and hopefully find a good answer for this problem.
Try this until a non-no answer appears:
function parent() {
this.child;
interestingProperty = "5";
...
}
function child() {
this.parent;
...
}
a = new parent();
a.child = new child();
a.child.parent = a; // this gives the child a reference to its parent
alert(a.interestingProperty+" === "+a.child.parent.interestingProperty);
You will need the child to store the parents this variable. As the Parent is the only object that has access to it's this variable it will also need a function that places the this variable into the child's that variable, something like this.
var Parent = {
Child : {
that : {},
},
init : function(){
this.Child.that = this;
}
}
To test this out try to run this in Firefox's Scratchpad, it worked for me.
var Parent = {
data : "Parent Data",
Child : {
that : {},
data : "Child Data",
display : function(){
console.log(this.data);
console.log(this.that.data);
}
},
init : function(){
this.Child.that = this;
}
}
Parent.init();
Parent.Child.display();
Just in keeping the parent value in child attribute
var Foo = function(){
this.val= 4;
this.test={};
this.test.val=6;
this.test.par=this;
}
var myObj = new Foo();
alert(myObj.val);
alert(myObj.test.val);
alert(myObj.test.par.val);
when I load in a json object I usually setup the relationships by iterating through the object arrays like this:
for (var i = 0; i < some.json.objectarray.length; i++) {
var p = some.json.objectarray[i];
for (var j = 0; j < p.somechildarray.length; j++) {
p.somechildarray[j].parent = p;
}
}
then you can access the parent object of some object in the somechildarray by using .parent
精彩评论