- How to determine if object is in array [duplicate]
- 6+ Ways to Find an Object in an Array of Objects Using JavaScript
- All Methods to Find an Object From an Array of Objects
- Find an Object From an Array by ID Using find() Method
- Using JavaScript filter() to Find an Object in Array
- Using findIndex() to Find an Object in Array by Index
- Using JavaScript forEach() Method to Find an Object
- Using JavaScript for…of Loop to Find an Object
- Find an Object Matching All Values in an Array of Objects
- Conclusion
How to determine if object is in array [duplicate]
now the «carBrands» array contains all instances. I’m now looking a fast solution to check if an instance of car1, car2, car3 or car4 is already in the carBrands array. eg:
var contains = carBrands.Contains(car1); //
car1 and car4 contain the same data but are different instances they should be tested as not equal. Do I have add something like a hash to the objects on creation? Or is there a faster way to do this in Javascript. I am looking for the fastest solution here, if dirty, so it has to be 😉 In my app it has to deal with around 10000 instances. no jquery
Are you going to be checking based on dictionaries, or do you want to test using names? You could using a hash for carBrands , and then just testing on the keys you want.
This question is different from the duplicate because it deals with objects rather than primitives. Using a simple === will only work in the simplest case where you have exact references to the objects in the array.
The caveats of using includes with objects have been addressed in How do I check if an array includes a value in JavaScript? multiple times. Some of the answers here don’t even consider this caveat. I don’t see a reason why this shouldn’t be closed as a duplicate. It does more harm than good to separate these questions by use case and leave the object reference caveat entirely unaddressed by one question, just because it doesn’t explicitly ask about object references.
18 Answers 18
function containsObject(obj, list) < var i; for (i = 0; i < list.length; i++) < if (list[i] === obj) < return true; >> return false; >
In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:
function containsObject(obj, list) < var x; for (x in list) < if (list.hasOwnProperty(x) && list[x] === obj) < return true; >> return false; >
This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.
+1. My answer was missing the point. This is the right one. (as a side note you can do exactly what the OP did extending Array.prototype)
@MartínNieva Probably because the object you're looking for isn't in the list, but rather a different object that compares as deeply-equal. In that case, using lodash's isEqual() would be preferable to abusing serialization. (In fact, using lodash, this whole solution becomes a one-liner, combining _.some and _.isEqual : _.some(list, v => _.isEqual(v, o)) .)
Why don't you use the indexOf method of javascript arrays?
It will return you the index (position in the array) of car1. It will return -1 if car1 was not found in the array.
Edit: Note that in the question, the requirements are to check for the same object referenced in the array, and NOT a new object. Even if the new object is identical in content to the object in the array, it is still a different object. As mentioned in the comments, objects are passed by reference in JS and the same object can exist multiple times in multiple structures.
If you want to create a new object and check if the array contains objects identical to your new one, this answer won't work (Julien's fiddle below), if you want to check for that same object's existence in the array, then this answer will work. Check out the fiddles here and in the comments.
6+ Ways to Find an Object in an Array of Objects Using JavaScript
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.
- Use find() method to find your object.
- Use filter() method to filter out the array.
- Use findIndex() method to find the object by its index.
- Use forEach() method to search for the object.
- Use for. of to loop through the array.
- 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.
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.
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);
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);
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.
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]);
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);
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);
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);
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.
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);
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);
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:
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 userJavascript object in array search === searchObjJavascript object in array search; >); >); console.log(obj);
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.
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.