6+ Ways to Find an Object in an Array of Objects Using JavaScript

Robin
September 16, 2022

We need to work with objects and find a specific object in an array of objects using JavaScript. You can use many JavaScript methods to search for an object.

The find() method can be used to find an object from an array. This method searches for a specific object by its id or other property values inside the array. If it finds the object, it returns that.

You can also search for an object by matching all property values with other objects in a JavaScript array. In this way, you will get an identical object from the array that matches all the values, not a single property value.

In this article, we will go through all the methods that we can use to find an object in an array of objects using JavaScript.

All Methods to Find an Object From an Array of Objects

There are many methods and techniques available in JavaScript to extract an object from an array of objects. You have to loop over an array of objects to find one by using the property values.

I will show you 6 techniques that you can use in your project. These are:

  1. Use find() method to find your object.
  2. Use filter() method to filter out the array.
  3. Use findIndex() method to find the object by its index.
  4. Use forEach() method to search for the object.
  5. Use for...of to loop through the array.
  6. Match all properties and values of an object.

To test all these techniques, I will use the users array with 6 properties i.e. id, firstname, lastname, username, email and age. This array has 5 items.

          const users = [
    {
        id: 1,
        firstname: 'john',
        lastname: 'doe',
        username: 'johnd',
        email: 'john@gmail.com',
        age: 35
    },
    {
        id: 2,
        firstname: 'david',
        lastname: 'morrison',
        username: 'mor_2314',
        email: 'morrison@gmail.com',
        age: 27
    },
    {
        id: 3,
        firstname: 'kavin',
        lastname: 'ryan',
        username: 'kavin@gmail.com',
        email: 'kevinryan',
        age: 35
    },
    {
        id: 4,
        firstname: 'william',
        lastname: 'hopkins',
        username: 'william56',
        email: 'william@gmail.com',
        age: 43
    },
    {
        id: 5,
        firstname: 'jimmie',
        lastname: 'klein',
        username: 'jimmie_k',
        email: 'jimmie@gmail.com',
        age: 21
    },
];
        

We will loop through this users array using different JavaScript methods to find a specific object. We will also loop through objects in JavaScript to match all properties and values to find an identical object.

How to Find an Object in an Array of Objects Using JavaScript

Find an Object From an Array by ID Using find() Method

The find() is a JavaScript array method. Using this method, I will loop through our users array. You will have access to each user inside the callback function.

When the callback function returns true, the find() method will return that user object available in the callback function at that time.

Now we can check those objects by their id or any other properties. If any of these objects match our search term, the callback function will return true. In this way, the find() method will return the object that matches our search.

Find an Object by ID

          const obj = users.find((user) => {
    return user.id === 3;
});

console.log(obj);
        

Output:

          {
  id: 3,
  firstname: 'kavin',
  lastname: 'ryan',
  username: 'kavin@gmail.com',
  email: 'kevinryan',
  age: 35
}
        

I am searching for an object by its id in this example. Inside the callback function, I am checking if the user.id is equal to 3 or not.

When the callback function finds an object whose user.id is equal to 3, it will return true and the obj variable will store that user. If there is no object with that id, the find() method will return undefined.

Find an Object by Username

          const obj = users.find((user) => {
    return user.username === 'william56';
});

console.log(obj);
        

Output:

          {
  id: 4,
  firstname: 'william',
  lastname: 'hopkins',
  username: 'william56',
  email: 'william@gmail.com',
  age: 43
}
        

If you don't want to find by id, you can also use any other properties like username. Everything is the same. Just instead of using user.id, I am using user.username to match with a username.

But it is good to use a property that has unique value across all objects in the array.

Because if we search by the firstname, multiple user objects might have the same firstname. The find() method will only return the first object that matches. It will ignore other matched objects.

If you want to get all the objects that match the search term, you can use the filter() method in JavaScript.

Also Read: 6 Ways to Check If an Object Has a Property/Key in JavaScript

Using JavaScript filter() to Find an Object in Array

The filter() method works like the find() method in JavaScript. The only difference is that this method returns a new array will the matching objects.

          const objArray = users.filter((user) => {
    return user.id === 3;
});

console.log(objArray[0]);
        

Output:

          {
  id: 3,
  firstname: 'kavin',
  lastname: 'ryan',
  username: 'kavin@gmail.com',
  email: 'kevinryan',
  age: 35
}
        

When I search by user.id using the filter() method, it will return an array with a single object. Because there is one object that has an id equal to 3.

But when I try to find the object whose age is equal to 35, it will return an array with 2 objects. Using the filter() method, you can get multiple matching objects.

          const objArray = users.filter((user) => {
    return user.age === 35;
});

console.log(objArray);
        

Output:

          [
  {
    id: 1,
    firstname: 'john',
    lastname: 'doe',
    username: 'johnd',
    email: 'john@gmail.com',
    age: 35
  },
  {
    id: 3,
    firstname: 'kavin',
    lastname: 'ryan',
    username: 'kavin@gmail.com',
    email: 'kevinryan',
    age: 35
  }
]
        

Using findIndex() to Find an Object in Array by Index

You can find the index of the object that you are looking for. Then using that index value, you can get the object from the users array.

To get the index JavaScript has the findIndex() method for an array.

          const index = users.findIndex((user) => {
    return user.id === 3;
});

console.log(index);
// 2

const obj = users[index];

console.log(obj);
        

Output:

          {
  id: 3,
  firstname: 'kavin',
  lastname: 'ryan',
  username: 'kavin@gmail.com',
  email: 'kevinryan',
  age: 35
}

        

This method returns the index number. In this case, I am looking for an object whose id is equal to 3. Therefore, I am getting 2 as its index from this method.

Now, I can dynamically access the object in JavaScript using the index variable. You can also use other properties other than id.

Note: If the findIndex() method doesn't find any match, it will return -1.

Using JavaScript forEach() Method to Find an Object

The forEach() method is used to loop through an array in JavaScript. We can use this method to loop through our users array. But it doesn't return the matching items automatically like previous methods.

With this method, you have to check and get the matching object manually. It might sound complex but it's not. It is also very simple to use.

          let obj = {};

users.forEach((user) => {
    if (user.id === 4) {
        obj = { ...user };
    }
});

console.log(obj);
        

Output:

          {
  id: 4,
  firstname: 'william',
  lastname: 'hopkins',
  username: 'william56',
  email: 'william@gmail.com',
  age: 43
}
        

You need to declare a variable outside the forEach() method. I have declared the obj variable which is an empty object with the let keyword.

I am using let because I will reassign its value when I find a matching object inside the forEach() method.

I am checking whether the user.id is equal to 4 or not using the if condition. If the condition matches, I will reassign the obj variable value by spreading the user object with spread syntax in JavaScript.

Also Read: Best Ways to Create Dynamic HTML Element & CSS in JavaScript

Using JavaScript for…of Loop to Find an Object

There are different for loops in JavaScript. For an array, you can use the for..of loop and traditional for loop. I will show you how you can find an object from an array using both for loops.

Using for...of Loop

In for...of loop, you need to declare a variable outside the loop. Because inside the loop, you have to check and select the matching object.

          let obj = {};

for (const user of users) {
    if (user.id === 3) {
        obj = { ...user };
    }
}

console.log(obj);
        

Output:

          {
  id: 3,
  firstname: 'kavin',
  lastname: 'ryan',
  username: 'kavin@gmail.com',
  email: 'kevinryan',
  age: 35
}
        

Inside the for...of loop, I am accessing each user object with the user variable. Now, I can check for user.id with the if condition. When it finds a match, it will store that object in the obj variable.

Using for Loop

You can use a traditional for loop instead of using for...of in JavaScript. It will also give you the same result. You need to follow the same process starting with declaring a variable for the object.

          let obj = {};

for (let i = 0; i < users.length; i++) {
    if (users[i].username === 'mor_2314') {
        obj = { ...users[i] };
    }
}

console.log(obj);
        

Output:

          {
  id: 2,
  firstname: 'david',
  lastname: 'morrison',
  username: 'mor_2314',
  email: 'morrison@gmail.com',
  age: 27
}
        

In this example, I am looking for an object by its username inside the if condition. When it finds a matching username, it will store that object in the obj variable using spread syntax.

Find an Object Matching All Values in an Array of Objects

You can find an identical object from an array of objects by matching all the properties and values. Without searching by a single property value, I will find an object by using another object.

This technique will give you a user object from the users array, that matches the following object:

          const searchObj = {
    id: 4,
    firstname: 'william',
    lastname: 'hopkins',
    username: 'william56',
    email: 'william@gmail.com',
    age: 43,
};
        

Our matching object has to have all the properties of the searchObj object. It also needs to match the property values with this searchObj object.

In any case, if you have such requirements in your project, you can use this technique. If objects in the array have more or fewer properties as well as don't match a single property value, this technique will not consider that object as a match.

          const searchObj = {
    id: 4,
    firstname: 'william',
    lastname: 'hopkins',
    username: 'william56',
    email: 'william@gmail.com',
    age: 43,
};

const obj = users.find((user) => {
    return Object.keys(searchObj).every((key) => {
        return user[key] === searchObj[key];
    });
});

console.log(obj);
        

Output:

          {
  id: 4,
  firstname: 'william',
  lastname: 'hopkins',
  username: 'william56',
  email: 'william@gmail.com',
  age: 43
}

        

I am calling the find() method on the users array to get access to the individual user object. I am getting all the keys from the searchObj object using Object.keys() method. It will return an array of keys.

          [ 'id', 'firstname', 'lastname', 'username', 'email', 'age' ]
        

Using those keys, I will be able to loop through the object and dynamically access the object property in JavaScript. I am calling every() method on this array of keys.

In this way, I will get true if all the properties and values of the user object match with the searchObj object. It will return false if all the properties and values don't match each other.

Finally, if there is an object in the users array that matches everything with the searchObj object, the find() method will return that object and store it in the obj variable.

Also Read: How to Remove Elements From an Array in JavaScript

Conclusion

You have seen 6 different ways to search for an object in a JavaScript array. If you want to find multiple objects filter() method will be a good choice.

But if you want to search using a unique property and you know there will be only one object, the find() method will do the job.

Other than these, there are findIndex(), forEach() and for...of loop in the JavaScript. These methods are also useful for looping through an array.

You can also find an identical object by matching all the properties and values with another object other than finding it by a single value. In this way, you will get exactly alike objects.

You can use any of these methods to find an object in an array of objects using JavaScript according to the requirements of your application.

Related Posts