Lutfor Rahman Lutfor Rahman - 7 months ago 9
Javascript Question

Getting Parent Object, from nested value

what javascript code could you use to return person1 object providing id parameter 1 or person2 object providing id parameter 2?

{
person1:
{
id: 1,
name: 'john'
},
person2:
{
id: 2,
name: 'doe'
}
}

Answer

You can just loop through them using foreach.. Lets say we had your object here:

var obj = {
  person1: {
    id: 1,
    name: 'john'
  },
  person2: {
    id: 2,
    name: 'doe'
  }
}

Then you just loop and find the one.. so lets say you had the ID.

var ID = 2;
for (var i in obj) {
   if(obj[i].id == ID){
    result = obj[i]; //this is person2...
   }
}

I Hope this is what you are asking for.. your question wasnt very clear.