Lodash _.keyBy Method Example

_.keyBy is a very useful method. It helps a lot when trying to get an object with a specific property. Let’s say we have 100 users and we want to get the user with Id 1.

Learn Lodash JS at Lodash JS Tutorial with Examples.

Lodash _.keyBy Method Example

<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
        var users = [
    { id: 1, firstName: "John", lastName: "Doe", age: 28, gender: "male" },
    { id : 2, firstName: "Jane", lastName: "Doe", age: 5, gender: "female" },
    { id : 3, firstName: "Jim", lastName: "Carrey", age: 54, gender: "male" },
    { id : 4, firstName: "Kate", lastName: "Winslet", age: 40, gender: "female" }
        ];
        
        users = _.keyBy(users, "id");
  
        var user = users[1];
        console.log(user);
    </script>
</head>
<body></body>
</html>
Output:
{id: 1, firstName: "John", lastName: "Doe", age: 28, gender: "male"}

Reference


Comments