乐闻世界logo
搜索文章和话题

How to filter array of objects that contains string using lodash

1个答案

1

We can use the filter and includes methods from Lodash to achieve this.

For example, consider the following array of objects, where each object represents an employee with their name and department:

javascript
const employees = [ { name: "Alice", department: "Engineering" }, { name: "Bob", department: "HR" }, { name: "Charlie", department: "Engineering" } ];

Now, our task is to find all employees working in the Engineering department. We can write the code as follows:

javascript
import _ from 'lodash'; // Define a filtering condition function function isInEngineering(employee) { return _.includes(employee.department, 'Engineering'); } // Apply the filter using Lodash const engineeringEmployees = _.filter(employees, isInEngineering); console.log(engineeringEmployees);

This code first defines a function called isInEngineering which checks if the employee's department contains the string 'Engineering'. Then, we use the _.filter method with the employees array and our filtering condition function isInEngineering. Finally, we print the filtered results.

Executing this code will produce the following output:

javascript
[ { name: "Alice", department: "Engineering" }, { name: "Charlie", department: "Engineering" } ]

This successfully filters all employees working in the Engineering department from the array. Using the filter and includes methods from Lodash makes this process intuitive and efficient.

2024年8月24日 01:32 回复

你的答案