find specific object in a array by id in javascript

You can use Array.find() method to find a specific Object in an array by its id.

Let's say you have an array of objects like this:

index.tsx
const data = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Jane'},
  {id: 3, name: 'Bob'},
];
92 chars
6 lines

To find an object with a specific id in this array, you can use the Array.find() method:

index.tsx
const id = 2;
const result = data.find(obj => obj.id === id);
console.log(result); // {id: 2, name: 'Jane'}
108 chars
4 lines

In this example, we are looking for an object where the id property matches the id variable (which is 2 in this case). The find() method returns the first object that satisfies the condition (or undefined if none is found).

You can also use the Array.filter() method to find all objects in the array with a specific id:

index.tsx
const id = 2;
const result = data.filter(obj => obj.id === id);
console.log(result); // [{id: 2, name: 'Jane'}]
112 chars
4 lines

In this example, the filter() method returns an array with all objects that match the condition (in this case, only one object with id equal to 2).

gistlibby LogSnag