how.wtf

Search across all object values in an array in JavaScript

· Thomas Taylor

If there is a need to search across all object values in an array in JavaScript, a combination of filter, entries, and some can be used.

How to search across object values

In a frontend data table, rows may contain information about people:

 1const people = [
 2  {
 3    "id": 5,
 4    "firstName": "Buzz",
 5    "lastName": "Lightyear2"
 6  },
 7  {
 8    "id": 2,
 9    "firstName": "Buzz",
10    "lastName": "Lightyear"
11  },
12  {
13    "id": 1,
14    "firstName": "Woody",
15    "lastName": "Pride"
16  },
17  {
18    "id": 3,
19    "firstName": "Potato",
20    "lastName": "Head"
21  },
22  {
23    "id": 4,
24    "firstName": "Slinky",
25    "lastName": "Dog"
26  }
27];

To provide a “search” across all of the values, use the following:

1const query = "Slinky".toLowerCase();
2const results = people.filter(o => Object.entries(o).some(e => String(e[1]).toLowerCase().includes(query)));
3console.log(results); // [ { id: 4, firstName: 'Slinky', lastName: 'Dog' } ]

If id or other fields are not preferable in the search, use the rest operator.

1const query = "Slinky".toLowerCase();
2const results = people.filter(o => {
3  const { id, ...rest } = o;
4  return Object.entries(rest).some(e => String(e[1]).toLowerCase().includes(query))
5});
6console.log(results); // [ { id: 4, firstName: 'Slinky', lastName: 'Dog' } ]

#Javascript  

Reply to this post by email ↪