Determine if an object is present in a JavaScript array
This post will discuss how to determine whether an object is present in a JavaScript array.
JavaScript native methods indexOf() and includes() compare by using the strict equality operator (===). This won’t work for object comparison, as shown below:
|
1 2 3 4 |
var key1 = { name : 'Joey' }; var key2 = { name : 'Joey' }; console.log(key1 === key2); // false |
This post provides an overview of some of the available alternatives to accomplish this.
1. Using _.some() method
If you’re already using the Lodash library, consider using the _.some method. It returns true if a JavaScript array contains an object.
|
1 2 3 4 5 6 7 8 9 10 |
var _ = require('lodash'); var obj = [{ one : 1 }, { two : 2}, { three : 3 }]; var key = { two : 2}; console.log(_.some(obj, key)); /* Output: true */ |
Alternatively, you can use the _.some method of the Underscore library.
|
1 2 3 4 5 6 7 8 9 10 |
var _ = require('underscore'); var obj = [{ one : 1 }, { two : 2}, { three : 3 }]; var key = { two : 2}; console.log(_.some(obj, key)); /* Output: true */ |
2. Using JSON.stringify() function
Here, the idea is to convert the given object into a string using the JSON.stringify() method. Then we compare the string representation of the object against each entry in the array using the strict equality operator (===). This can be done using any of the methods discussed here.
|
1 2 3 4 5 6 7 8 9 10 11 |
var obj = [{ one : 1 }, { two : 2}, { three : 3 }]; var key = { two : 2}; var str = JSON.stringify(key); var isPresent = obj.some(item => JSON.stringify(item) === str); console.log(isPresent); /* Output: true */ |
That’s all about checking if an object is present in a JavaScript array.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)