0

I have an array of objects and a unique id. I'd like to search through the array of objects for the object instance that matches the unique id, but I'm not sure how to begin to approach it.

idToSearchfor = 2

arrayToBeSearched = [{content: 'string', id: 1}, {content: 'string', id: 2}, {content: 'string', id: 3}]
Jack Collins
  • 339
  • 1
  • 2
  • 13
  • 1
    You can use [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) for that. – Titus May 09 '19 at 18:22
  • 3
    Possible duplicate of [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – James May 09 '19 at 18:30

1 Answers1

4

That's what Array.prototype.find() is for, assuming you're certain you will never have more than one matching item (find only returns the first matching item):

let idToSearchfor = 2;

const arr = [{content: 'string', id: 1}, {content: 'string', id: 2}, {content: 'string', id: 3}]

console.log(arr.find(x=>x.id===idToSearchfor));

Otherwise (several possible matches), use Array.prototype.filter():

let idToSearchfor = 2;

const arr = [{content: 'string', id: 1}, {content: 'string', id: 2}, {content: 'string', id: 3}]

console.log(arr.filter(x=>x.id===idToSearchfor));
connexo
  • 53,704
  • 14
  • 91
  • 128