Jack Collins
Jack Collins

Reputation: 421

How can I search through an array of objects for a unique id?

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}]

Upvotes: 0

Views: 49

Answers (1)

connexo
connexo

Reputation: 56753

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));

Upvotes: 4

Related Questions