How To Find an object by id in an array of Javascript Objects – Definitive Guide?

Javascript arrays allow storing a collection of multiple items under a single name.

You can find an object by id in an array of JavaScript objects using array.find(item => item.id === 'idValue') function.

There are multiple ways to find an object by id in an array of JavaScript objects.

If You’re in Hurry…

You can use the code snippet to find an object by id in an array of javascript objects.

    let birdsObj = [{
     id: '100',
     name: 'owl'
    }, {
        id: '101',
      name: 'dove'
    }, {
        id: '102',
      name: 'parrot'
    }];

    var bird = birdsObj.find(bird => bird.id === '100');
    console.log(bird);

Output

    { id: "100", name: "owl" }

If You Want to Understand Details, Read on…

Using Find() Method

Find() method returns the first element in the array that satisfies the provided condition. If no value meets the condition, undefined is returned.

If you want to check an element’s presence in an array before extracting the value, read how to check if an item exists in an array in JavaScript.

Code

    let birdsObj = [{
     id: '100',
     name: 'owl'
    }, {
        id: '101',
      name: 'dove'
    }, {
        id: '102',
      name: 'parrot'
    }];

    const id = '100';

    var bird = birdsObj.find(bird => bird.id === id);

    console.log(bird);

You can see the.find() method accepts a function with a condition to match a specific id.

The first array object(id=100) satisfies the condition inside the .find() and it is returned.
Output

    { id: "100", name: "owl" }

Let us see another way of implementing.find() method using Underscore.js
Code

    let birdsObj = [{
     id: '100',
     name: 'owl'
    }, {
        id: '101',
      name: 'dove'
    }, {
        id: '102',
      name: 'parrot'
    }];

    const id = '100';

    var birdObj = _.find(birdsObj, function(obj) {

         return obj.id == id;

    });

    console.log(birdObj);

Output

    { id: "100", name: "owl" }

Using FindIndex() Method

The findIndex() method returns the index of the first element in an array that satisfies the provided condition.
If no elements pass the condition, -1 is returned.

Code

    let birdsObj = [{
     id: '100',
     name: 'owl'
    }, {
        id: '101',
      name: 'dove'
    }, {
        id: '102',
      name: 'parrot'
    }];

    const id = '100';

    var birdIndex = birdsObj.findIndex(bird => bird.id === id);

    console.log("Index of Id 102 : "+birdIndex);

    console.log(birdsObj[birdIndex]);

Output

    "Index of Id 102 : 0"
    { id: "100", name: "owl" }

The .findIndex() method is similar to previous .find() method, which also accepts a function with a condition to match a specific id.

In this case, you will get the index position of the javascript object in the array, and the index position can be used to get the value from the array(birdsObj[birdIndex]).

Using Filter() Method

Filter method returns a new array based on the elements that get passed through the filter condition.

Code

    let birdsObj = [{
     id: '100',
     name: 'owl'
    }, {
        id: '101',
      name: 'dove'
    }, {
        id: '102',
      name: 'parrot'
    }];

    const id = '100';

    var bird = birdsObj.filter(bird => bird.id === id);

    console.log(bird);

Output

    [{ id: "100", name: "owl" }]

In the above example, .filter() method returns the first array object(birdsObj) as the value of object’s id field matches with the conditional value(id='100).

Using For Loop

One of the traditional ways to find an object by id in an array is by iterating the array using for loop.

Code

    let birdsObj = [{
     id: '100',
     name: 'owl'
    }, {
        id: '101',
      name: 'dove'
    }, {
        id: '102',
      name: 'parrot'
    }];

    const id = '100';

    for (var i = 0, len = birdsObj.length; i < len; i++) {

        if(birdsObj[i].id === id){

          console.log(birdsObj[i]);

          break;

        }
    } 

Output

    { id: "100", name: "owl" }

Here, the JavaScript object array is iterated using for loop and a condition(birdsObj[i].id === id) is added to check for matching id value.

Using Reduce() Method

Reduce executes the supplied reducer callback function on each element of the array in order and passes the return value from the calculation on the preceding element.

Code

    let birdsObj = [{
     id: '100',
     name: 'owl'
    }, {
        id: '101',
      name: 'dove'
    }, {
        id: '102',
      name: 'parrot'
    }];

    const id = '100';

    const bird = birdsObj.reduce(function(a, b){

        return (a.id==id && a) || (b.id == id && b)

    });

    console.log(bird);

Output

    { id: "100", name: "owl" }

In this example, the .reducer() function iterates through the array by executing the callback function.

The callback function takes two parameters(previousValue and currentValue), and here a condition is added to check the id value with of previousValue or currentValue of reduce function.

previousValue constantly gets updated based on the condition while iterating through the reducer() method.

If the object’s previous or current id value matches the findId(id), it will be returned.

Using Map() Method

The Map() method creates a new array with the results of the provided function on every element in the calling array.
Map() method is one of the least helpful ways to find an object by id in an array in Javascript.

Code

    let birdsObj = [{
     id: '100',
     name: 'owl'
    }, {
        id: '101',
      name: 'dove'
    }, {
        id: '102',
      name: 'parrot'
    }];

    const id = '100';

    const bird = birdsObj.map(item=> item.id===id ? item: null);

    console.log(bird);

    const birdObj=bird.filter(Boolean);

    console.log(birdObj);

Output

    [{ id: "100", name: "owl" }, null, null]
    [{ id: "100", name: "owl" }]

An array is iterated through the .map() method, and a function having a condition to match id is used to find the object.
A ternary condition(item=> item.id===id ? item: null) is added in order to make .map() method return the actual object on match found cases else to return null.
At last, the filter method can be used to get the object from the results of the .map() method.

JSfiddle

This tutorial is available in this JSFiddle.

Conclusion

In this tutorial, you’ve learned how to find an object by id in an array of JavaScript objects in Javascript. You’ve also known different ways to find an object by id in an array of JavaScript objects.

If you’ve any questions, please comment below.

You May Also Like

Leave a Comment