-2

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 ^^

Marouen Mhiri
  • 1,640
  • 1
  • 14
  • 20
  • The downvotes are because you haven't followed the [guidelines](https://stackoverflow.com/help) for posting questions. Edit your question and discuss what you've tried, what results you've gotten from your attempts, what you've found by using google, and why those potential solutions haven't worked for you. – SaganRitual Mar 11 '18 at 22:41
  • You can always loop through an array's key-value pairs and select those you need. – klenium Mar 11 '18 at 22:44

2 Answers2

0

I feel using something like match-sorter works prefect for these kind of use cases.

const result = matchSorter(MyArray, searchKey, { keys: ['name', 'prop', 'propx']}

No point reinventing the wheel, when someone already has done the work for you.

Hozefa
  • 1,676
  • 6
  • 22
  • 34
-1

You can use _.filter from lodash. https://lodash.com/docs#filter

DiPix
  • 5,755
  • 15
  • 61
  • 108