This should do.
You don’t have to loop through the array, you can use build-in functions like map
, some
and filter
to achieve this.
var data = [
{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
{id:1,first_name:'John',last_name:'Bal',age:20,birth:'1992-01-12'},
{id:2,first_name:'Blaan',last_name:'Adey',age:35,birth:'2001-04-16'}
];
var searchColumn = ['first_name','last_name','birth'];
var search = (searchParam) => {
// map here applies the function (value) => searchColumn.some(property => value[property] === searchParam) ? value : null
// over every value in the array & some loops through every value in the search column
// looking for an object where one of the properties specified in searchColumn has a value that matches our search parameter
return data.map(value => searchColumn.some(property => value[property] === searchParam) ? value : null)
.filter(result => !!result); // here we use filter to remove the null values mapped in the map function
}
search('John');
// result -> [{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
// -> {id:1,first_name:'John',last_name:'Bal',age:20,birth:'1992-01-12'}]
UPDATE: As suggested, an better solution:
var search = (searchParam) => {
return data.filter(value => !!searchColumn.some(property => value[property] === searchParam));
}
CLICK HERE to find out more related problems solutions.