0

This seems like a very simple question so I hope there's a simple solution!

If I have an array of objects:

let objArray = [
     {id: 2, name: Bob},
     {id: 4, name: James},
     {id: 3, name: Sally},
     {id: 9, name: Jenny}
]

If I then have another variable that tells me which object in the array I want, how would I go about using it?

let requiredObj = 2

I want to use this variable to return the name 'Bob'. So far I've been doing it by running a for loop and checking each of the ids against the requiredObj. This doesn't seem like the best way to do it, so was hoping there's a 'right way' that I'm not aware of?

  • 2
    `objArray.find(({ id }) => id === requiredObj)` – user120242 Jun 25 '20 at 10:50
  • You can use array methods such as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find with your own callback function that determines whether the current object is one you are looking for, if that makes you any happier than writing a loop yourself … – CBroe Jun 25 '20 at 10:51
  • I don't have a problem writing the loop myself, if that's the right way to do it, just felt very longhand! – RiddleRiddlerRddler Jun 25 '20 at 10:52
  • If you just want to take 3rd position(or the position in `requiredobj`) object do `const wantedObject = objArray[requiredObj]` – Jon Jun 25 '20 at 10:52
  • I'm not after the item in the third position, I'm looking for the object where id===requiredObj – RiddleRiddlerRddler Jun 25 '20 at 10:57
  • user120242 has given you the solution in the first comment… – deceze Jun 25 '20 at 10:58

0 Answers0