Reputation: 307
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'
}
}
Upvotes: 0
Views: 159
Reputation: 4646
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.
Upvotes: 1
Reputation: 780724
You can use a for
loop to iterate through the properties of an object.
var obj = {
person1:
{
id: 1,
name: 'john'
},
person2:
{
id: 2,
name: 'doe'
}
};
var id_to_find = 1;
var name_found;
for (var name in obj) {
if (obj[name].id == id_to_find) {
name_found = name;
break;
}
}
Upvotes: 3