0

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'
        }
    }
0

2 Answers 2

3

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;
    }
}
Sign up to request clarification or add additional context in comments.

11 Comments

Break...? In an if statement?
break is for the for loop.
That statement would give you. Error obj is not defined (Javascript Version)
@Dsafds obj is the object in the question.
@Barmar this is a good answer, and it works, you should not be downvoted
|
1

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.

4 Comments

Javascript doesn't have foreach.
obj is an object, not an array, you can't use obj.length or obj[i].
I meant it to become an object.... it has been a long time since i did javascript ok.. sometimes you mess up @Barmar
@LutforRahman actually if you see the edits i made on this anwser, i had previously had var on results.. results btw in this example is a global variable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.