Having an array like:
let MyArray = [{
id: 1, name: 'xx', age: '20', prop: val, propx: valx
},
{
id: 2, name: 'yy', age: '30', prop: val2, propx: valy
},
{
id: 3, name: 'zz', age: '40', prop: val3, propx: valz
}]
How can one filter this array to get the result of a search depending on the object properties? I want to write a function in this form and have the filtered result from myArray
:
search(myArray, ['name', 'prop', 'propx'], searchKey)
The condition should be:
MyArray[i][name].indexOf(searchKey) > -1 || MyArray[i][prop].indexOf(searchKey) > -1 || MyArray[i][propx].indexOf(searchKey) > -1)
Is there a possibility to generate this OR rule dynamically? What I've already did is:
MyArray.filter((item) => item['name'].indexOf('x') > -1 || item['prop'].indexOf('x') > -1))
this works already but it's not dynamic because if I want to search for the 'propx' I have to rewrite the condition like that:
item['name'].indexOf('x') > -1 || item['prop'].indexOf('x') > -1 || item['propx'].indexOf('x') > -1
It looks like a recursion but I can't think anymore ^^