How to Find an ID from an Array in JavaScript?

Estimated read time 2 min read

You can use a for loop or the Array.prototype.find() method in JavaScript to find an object in an array by its ID.

Here’s an example that demonstrates how to find an object in an array by its ID using a for loop:

const persons = [
  { id: 1, name: "Jim" },
  { id: 2, name: "Jane" },
  { id: 3, name: "John" },
];

let person;

for (let i = 0; i < persons.length; i++) {
  if (persons[i].id === 2) {
    person = persons[i];
    break;
  }
}

console.log(person);
/*
Output:
{ id: 2, name: "Jane" }
*/

In this example, the for loop iterates over the persons array, and the if statement checks if the id of each object in the array is equal to 2. If the id of an object is equal to 2, the person variable is assigned the value of the object and the loop is broken.

Here’s an example that demonstrates how to find an object in an array by its ID using the Array.prototype.find() method:

const persons = [
  { id: 1, name: "Jim" },
  { id: 2, name: "Jane" },
  { id: 3, name: "John" },
];

const person = persons.find((p) => p.id === 2);

console.log(person);
/*
Output:
{ id: 2, name: "Jane" }
*/

In this example, the Array.prototype.find() method is used to find the first object in the persons array that satisfies the provided testing function, which is p => p.id === 2. The find() method takes a callback function as its argument, and the callback function is called for each element in the array until the callback function returns true for an element. If an object is found that satisfies the testing function, the find() method returns the object. If no object is found, the find() method returns undefined.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply