![]() ![]() So, we need to assign the extracted value to a variable in order to access it, as shown below: let obj = students.find(student => student.name = 'John') The “find” method does not affect the original “students” array, but just extracts the first element that matches the condition. Instead of using an “if” statement, we can just give the condition we need checked for every iteration. Let’s use the same array of objects example as above, but now, we’re going to attach the “find” method to that array.įor every iteration, the method creates a temporary “student” variable that contains an element of the array (in this case, the student object) in order. This is a pre-defined JavaScript method for arrays, and it can be used to return the first occurrence of the element that confirms to the given condition. By using the “find” method, we can finish everything in just one line of code. Though the forEach method simplifies things a bit, we’re still using too many lines of code. Using the find method to search an array of objects When we run the above lines of code, we’ll get: If that’s the case, let’s print out that object. So, we’ll loop through 0 to array.length-1.įor every iteration of the loop, let’s check whether the “name” property of the object in that particular iteration is equal to “John” (our condition). ![]() Start the loop from 0 because array indices start from 0 but stop right before the length of the array. Now, you can just use a for loop to loop through this array. Let’s say we have an array “students”, and within it, we have data on each student in the form of an object. Looping is a very common way of doing this. Or you can just determine if that particular property value is present in one of the objects in the array and return true if that is the case. ![]() For example, you can match one of the property values and extract the object that contains that value. There are multiple ways to search for the properties inside of an object. In this tutorial, let’s look at how to use JavaScript to search an array of objects. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |