Languages
[Edit]
EN

JavaScript - find and return object from Array using lodash

0 points
Created by:
cory
1786

In this article, we would like to show you how to find and return object from Array using lodash in JavaScript.

Practical examples

Example 1 - find object by id property value

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
  <script>

    var objects = [
        { id: 1, name: 'a' },
        { id: 2, name: 'b' },
        { id: 3, name: 'c' }
    ];

    var idToFind = 2;
    var object = _.find(objects, { id: idToFind }); // find by id

    console.log(JSON.stringify(object, null, 4));

  </script>
</body>
</html>

Example 2 - find object by name property value

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
  <script>

    var objects = [
        { id: 1, name: 'a' },
        { id: 2, name: 'b' },
        { id: 3, name: 'c' }
    ];

    var nameToFind = 'c';
    var object = _.find(objects, { name: nameToFind }); // find by name

    console.log(JSON.stringify(object, null, 4));

  </script>
</body>
</html>

 

References

  1. Lodash Documentation - find

Alternative titles

  1. JavaScript - use lodash to find and return object from Array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join