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)
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.
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.
Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With