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)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…