DEV Community

Sam Newby
Sam Newby

Posted on

Using `find()` on an array of Objects in JavaScript

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');
Enter fullscreen mode Exit fullscreen mode

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs