W3jar
343 words
2 minutes

How to Find an Object by ID in an Array of JavaScript Objects

To find an object by its id in an array of JavaScript objects, you can use the find() method. This method is perfect for searching through an array and locating an element that matches a specific condition.

Here’s a step-by-step guide and example code to find an object by id:

Example Array and Function#

Suppose you have an array of objects like this:

const objectsArray = [
    { id: 1, name: "Alice", age: 25 },
    { id: 2, name: "Bob", age: 30 },
    { id: 3, name: "Charlie", age: 35 },
];

You can define a function to find an object by its id as follows:

function findObjectById(arr, id) {
    return arr.find((obj) => obj.id === id);
}

// Example usage:
const idToFind = 2;
const result = findObjectById(objectsArray, idToFind);
console.log(result); // Output: { id: 2, name: 'Bob', age: 30 }

Explanation:#

  1. find() Method: The find() method iterates through each element in the array and returns the first element that satisfies the provided testing function. If no elements satisfy the condition, it returns undefined.

  2. Callback Function: The callback function obj => obj.id === id checks if the id property of the current object (obj) matches the id you’re searching for.

  3. Returning the Result: If the object with the specified id is found, it is returned; otherwise, undefined is returned.

Alternative Approach: Using for Loop#

If you need more control or want to avoid using higher-order functions, you can use a traditional for loop:

function findObjectById(arr, id) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === id) {
            return arr[i];
        }
    }
    return undefined;
}

// Example usage:
const idToFind = 2;
const result = findObjectById(objectsArray, idToFind);
console.log(result); // Output: { id: 2, name: 'Bob', age: 30 }

Explanation of for Loop:#

  1. Loop Through Array: Iterate through each object in the array.

  2. Condition Check: Check if the id of the current object matches the id you are searching for.

  3. Return Object: If a match is found, return the object immediately. If no match is found by the end of the loop, return undefined.

Both approaches are effective, but using find() is more concise and idiomatic in modern JavaScript.