You have hit an API endpoint to retrieve some data and you get back an array of Objects. Problem is, you need to find one of the objects in that array. You could write a loop that will loop through each element in the array and find the one you're looking for, we don't need to do that. We can do it in one line with JavaScript using the find()
method.
let frameworks = [
{ name: "Laravel", lang: "PHP" },
{ name: "Rails", lang: "Ruby" }
];
let laravel = frameworks.find(obj => obj.name === 'Laravel');
The find method is actually executing a function here and tests that function against each element in the array. Each element in the array is represented as obj
and then we're accessing the name
property of each element and testing if the name property is equal to the value of 'Laravel'. Once, we find the object that has a name property equal to 'Laravel', the object is assigned to the variable laravel
.
Pretty cool right? We can find the object we're looking for with one line of code. If you have just started out on the path to learning JavaScript, then I would still recommend learning how to write loops that will iterate over an array, but once you are confident with loops, the find()
method is perfect for keeping your code clean.
If you want to find out more about the find()
method, you can check out it's page on MDN. Enjoy.
Top comments (0)