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.