You may have seen yourself in this situation when coding in JavaScript: you have an array of objects, and you need to find some specific object inside this array based on some property of the object. There are A LOT of ways of achieving this, so I decided to put some of them together in this post to make it easy for you to pick up whatever works best for you. Let's check them out!
Looping through objects in JavaScript 20th Jun 2018. Once in a while, you may need to loop through Objects in JavaScript. The only way to do so before ES6 is with a for.in loop. The problem with a for.in loop is that it iterates through properties in the Prototype chain. When you loop through an object with the for.in loop, you need to check if the property belongs to the object.
First, let's say that we have this array of objects called 'objArray':
And let’s say that we want to get the object that has the id equal to 3, let’s see how we can achieve that.
If you want to use the plain old javascript you can create a function that iterates over the array and then return the object when the id matches with the one you’re looking for (or return null if it doesn’t find a matching result):
Then you can pass the array you want to lookup, the property you’re looking for and its value. In our case we would use it like this:
If you prefer using the newer ES6 functions, you can also use the built-in find function, so we can achieve the same result without the need to implement our own function to look up an object in an array:
DISCLAIMER: As basically everyone said in the comments, yes, you could use the filter function instead of find, it's equally simple, but the point of this article here is to get to know about the find function. If you don't know about the filter function and want to have a look on it instead, I also wrote this small article talking about it. =)
It makes thing easier than ever, HOWEVER, you should already know that ES6 is not supported by some older browsers, so you should pay a little attention to this. One of the things that you can do to avoid browser-compatibility problems when using ES6-only functions is to use an external javascript library such as Underscore.js, because such libraries implement ES6 functions in a way that allow us to use these functions without worrying about older browsers support (and as a plus, those kind of libraries may even have some additional cool functions too). Hitman absolution cd key generator steam.
If we opt to use Underscore.js, our code to find the object with the id equal to 3 changes to this:
Maybe you already use jQuery in your project, and if that is the case, you can use jQuery’s grep function to achieve our desired result, it goes like this:
If you’re already working with AngularJS, you can also use the $filter module to filter the array. Using AngularJS’s $filter, it looks like this:
Here’s a demo on jsFiddle for you to play around with.