Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects on all properties value

I am really surprised I haven't been able to find anything related to my question. I am looking for a fast way to filter my array of objects based on a user text input.

Assume I have this array:

let data = [{
  "id": 1,
  "first_name": "Jean",
  "last_name": "Owens",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 2,
  "first_name": "Marie",
  "last_name": "Morris",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 3,
  "first_name": "Larry",
  "last_name": "Wallace",
  "email": "[email protected]",
  "gender": "Male"
}];

User writes "s", the expected result would be:

let result = [{
  "id": 1,
  "first_name": "Jean",
  "last_name": "Owens",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 2,
  "first_name": "Marie",
  "last_name": "Morris",
  "email": "[email protected]",
  "gender": "Female"
}]

I could use the filter function in such a way:

let = searchText = "s";
    let result = data.filter(object=>{
      for (var property in object) {
        if (object.hasOwnProperty(property)) {
          return object[property].toString().toLowerCase().indexOf(searchText) !== -1;
        }
      }
    });

So I am wondering if there are better alternatives to this solution?

--Here is a working JsFiddle thanks to KoolShams

--Plunker for benchmark purposes (tested with 2k data)

like image 386
Yann Thibodeau Avatar asked Oct 02 '16 14:10

Yann Thibodeau


People also ask

How do you filter an array of objects by value?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you filter the value of an array?

The JavaScript filter array function is used to filter an array based on specified criteria. After filtering it returns an array with the values that pass the filter. The JavaScript filter function iterates over the existing values in an array and returns the values that pass.

Can we sort array of objects?

Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.


1 Answers

You could use Object.keys() and some() instead.

let data = [{
  "id": 1,
  "first_name": "Jean",
  "last_name": "Owens",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 2,
  "first_name": "Marie",
  "last_name": "Morris",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 3,
  "first_name": "Larry",
  "last_name": "Wallace",
  "email": "[email protected]",
  "gender": "Male"
}];

var result = data.filter(function(o) {
  return Object.keys(o).some(function(k) {
    return o[k].toString().toLowerCase().indexOf('s') != -1;
  })
})

console.log(result)
like image 147
Nenad Vracar Avatar answered Oct 01 '22 23:10

Nenad Vracar