简体   繁体   中英

accessing the parent object from the child object property in javascript

My problem . I have an object like this:

t.mainobject = {
    prop1: "",
    prop2: "",
    id: "1",
    prop3: [
        child1: {
            id: "111"
        },
        child2: {
            id: "112"
        }
    ]
};

only child1/child2 is visible to me whereas I donot know its parent object . I tried using underscore but have not found any method which can provide me the parent object .

thanks in advance for any advice/suggestion.

edit1:
all my child objects were created from multiple object so it end up as a flatten object.

like:

t.mainobject = {
    prop1: "",
    prop2: "",
    id: "1",
    prop3: [
        child1: {
            id: "111"
        },
        child2: {
            id: "112"
        }
    ]
};


t.mainobject1 = {
    prop1: "",
    prop2: "",
    id: "2",
    prop3: [
        child1: {
            id: "211"
        },
        child2: {
            id: "212"
        }
    ]
};

t.mainobject3 = {
    prop1: "",
    prop2: "",
    id: "1",
    prop3: [
        child1: {
            id: "311"
        },
        child2: {
            id: "312"
        }
    ]
};

Now I ended up with an array with :

[{id:"111"},{id:"112"}, {id:"211"},{id:"212"}, {id:"311"},{id:"312"}]

Now how can I able to get the parent object containing the child object using the id .

edit 2:

my solution :

var parent = _.filter(allParent, function(r){
            for(var i=0; i<r.posts.length; i++){
                if(r.posts[i].id === allChildPosts[index].id){
                    return r.id;
                }
            }
        });

it return me the parent object and now I can easily access any property.

This is not directly possible, because as far as JavaScript knows, child1 could be a property of any number of objects: therefore, the concept of a 'parent object' does not really make sense generally speaking.

What's more, if there are no references to the parent objects, they will be garbage-collected, so no hope to get back to them.

However, if you can have a list of all the potential parents of an object, you can search them all :

function findParent(child){
  for(var i=0; i < parents.length; i++){
    var mainobject = parents[i]; // a potential parent
    for(childName in mainobject.prop3){
      if(mainobject.prop3[childName].id === child.id){ // match found!
        return mainobject;
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM