Categories
JavaScript Answers

How to return reference to array item when searching an array of objects with JavaScript?

Spread the love

Sometimes, we want to return reference to array item when searching an array of objects with JavaScript.

In this article, we’ll look at how to return reference to array item when searching an array of objects with JavaScript.

How to return reference to array item when searching an array of objects with JavaScript?

To return reference to array item when searching an array of objects with JavaScript, we can use the JavaScript array find method.

For instance, we write:

const users = [{
  id: 1,
  name: 'name1'
}, {
  id: 2,
  name: 'name2'
}]
const user = users.find(u => {
  const {
    id,
    name
  } = u
  return id === 1 && name === 'name1'
})

We have the users array with some objects.

And we want to get the 1 with id w and name 'name1'.

To do this, we call find with a callback that returns id === 1 && name === 'name1'.

And then user will be the reference to the first entry of users.

Conclusion

To return reference to array item when searching an array of objects with JavaScript, we can use the JavaScript array find method.

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 *