find object in array with specific id in javascript

To find an object in an array based on a specific id, you can use the find method in JavaScript. Assuming your array of objects looks like this:

index.tsx
const objectArray = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
  { id: 3, name: "Bob" }
];
104 chars
6 lines

You can find the object with id = 2 by using the following code:

index.tsx
const objectId = 2;

const result = objectArray.find(obj => {
  return obj.id === objectId;
});

console.log(result); // { id: 2, name: "Jane" }
145 chars
8 lines

The find method searches the array for the first element that satisfies the provided testing function. In this case, the testing function is checking if the id of the object in the array matches the id we are searching for.

If the object with the specified id is not found, the find method will return undefined. So, you should always check if the result is not undefined before accessing its properties.

related categories

gistlibby LogSnag