Sathya Sathya - 1 month ago 8
React JSX Question

How to implement filter by filter by search multiple property values in javascript?

I want to get the result based on what i have entered in the input field. This search can be filter by multiple keys like firstName, lastName, emailId.

This is my array of object,

var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12@gmail.com"
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12@gmail.com"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12@gmail.com"
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12@gmail.com"
}
];


Javascript code,

resData.filter(data, function(item){
item.map(function(list, i) {
if (list.firstName.toLowerCase().indexOf(self.state.inputValue.toLowerCase()) === -1 || list.lastName.toLowerCase().indexOf(self.state.inputValue.toLowerCase()) === -1 || list.emailId.toLowerCase().indexOf(self.state.inputValue.toLowerCase()) === -1) {
return;
}
console.log(list);
});

});

Answer

You could iterate through the keys and return true for the filter if some value is found.

var resData = [{ firstName: "Jhon", lastName: "adam", emailId: "jhn12@gmail.com" }, { firstName: "Kyle", lastName: "Miller", emailId: "kl12@gmail.com" }, { firstName: "Jhonathan", lastName: "adam", emailId: "jadm12@gmail.com" }, { firstName: "Lewis", lastName: "harber", emailId: "lewh12@gmail.com" }],
    self = { state: { inputValue: 'adam' } },
    result = resData.filter(function (item) {
        return Object.keys(item).some(function (k) {
            return item[k].toLowerCase().indexOf(self.state.inputValue.toLowerCase()) !== -1;
        });
    });
   
console.log(result);

With predefined keys

var resData = [{ firstName: "Jhon", lastName: "adam", emailId: "jhn12@gmail.com" }, { firstName: "Kyle", lastName: "Miller", emailId: "kl12@gmail.com" }, { firstName: "Jhonathan", lastName: "adam", emailId: "jadm12@gmail.com" }, { firstName: "Lewis", lastName: "harber", emailId: "lewh12@gmail.com" }],
    self = { state: { inputValue: 'adam' } },
    result = resData.filter(function (item) {
        return ['firstName', 'lastName'].some(function (k) {
            return item[k].toLowerCase().indexOf(self.state.inputValue.toLowerCase()) !== -1;
        });
    });
   
console.log(result);

Comments