Categories
JavaScript Answers

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

Spread the love

Finding an object by ID or another property in an array of JavaScript objects is something that we’ve to do a lot in our JavaScript code.

In this article, we’ll look at how to find an object by ID in an array of JavaScript objects in our code.

Array.prototype.find

JavaScript arrays come with the find method to let us find an object in an array with the condition we specify in the callback and return the first instance of the object that meets the condition.

If the object with the given condition isn’t found, then it returns undefined .

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const obj = arr.find(x => x.id === 2)
console.log(obj)

arr is an array of objects with the id and foo properties.

Then we call the find method with a callback that returns the condition with the object we’re looking for.

The x parameter is the object that’s being iterated through to find the object.

Therefore, obj is:

{id: 2, foo: "bar"}

Array.prototype.findIndex

The findIndex method lets us find the item that matches the given condition, but it returns the index of the first instance of the element that meets the condition instead of returning the whole object.

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const index = arr.findIndex(x => x.id === 2)
console.log(index)

Then index is 1 since the callback specifies that we find the first object with the id property set to 2.

{id: 2, foo: "bar"}

Array.prototype.filter

The filter method also lets us find array entries that meet the given condition.

It returns an array with all the elements that meet th given condition.

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const results = arr.filter(x => x.id === 2)

The callback is the same as the other examples as it returns the condition of the items we want to find.

Then we get:

[
  {
    "id": 2,
    "foo": "bar"
  }
]

If we only want to get one element from the array, we can get it by index by writing:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const results = arr.filter(x => x.id === 2)
console.log(results[0])

Then we get:

{
  "id": 2,
  "foo": "bar"
}

Also, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const [result] = arr.filter(x => x.id === 2)

to destructure the first result from the returned array.

Conclusion

We can use native JavaScript array methods to find an object by ID in our code.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *