0

I'm having a bit of a problem trying to get the exact output.

const data = [{
    name: 'Alex Young',
    country: 'SE',
    nID: 424
    address: 'some address 12'
},{
    name: 'Martha Lewis',
    country: 'PT',
    nID: 312,
    address: 'an address 49'
},{
    name: 'Sophie Jones',
    country: 'NL',
    nID: 36,
    address: 'other address 3129'
}];

const filter = '12';

const keysToEvaluate = ['name', 'country', 'address'];

For the given data, I would like to evaluate only the given keysToEvaluate and output all objects where the values contains the filter.

expected output:

[{
    name: 'Alex Young',
    country: 'SE',
    nID: 424
    address: 'some address 12'
},{
    name: 'Sophie Jones',
    country: 'NL',
    nID: 36,
    address: 'other address 3129'
}]

TIA

  • See [here](https://stackoverflow.com/questions/13594788/javascript-filter-array-of-objects) for filtering an array by object properties, and [here](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) for accessing object properties using variables. – T.J. Crowder Mar 04 '20 at 15:02
  • Basically: `const result = array.filter(entry => keysToEvaluate.some(key => entry[key].includes(filter)));` I've assumed that *any* match means the object should be included. If *all* properties should match for an object to be kept, change `some` to `every`. – T.J. Crowder Mar 04 '20 at 15:02

1 Answers1

0

const data = [{name: 'Alex Young',country: 'SE',nID: 424,address: 'some address 12'},{name: 'Martha Lewis',country: 'PT',nID: 312,address: 'an address 49'},{name: 'Sophie Jones',country: 'NL',nID: 36,address: 'other address 3129'}];

    const filter = '12';

    const keysToEvaluate = ['name', 'country', 'address'];

    const filtered = data.filter(t => keysToEvaluate.some(k => String(t[k]).includes(filter)));
    console.log(filtered);
Yosef Tukachinsky
  • 5,570
  • 1
  • 13
  • 29
  • tweaked it so it becames case insensitive: ```const filtered = data.filter(t => keysToEvaluate.some(k => String(t[k].toLowerCase()).includes(filter.toLowerCase())));``` – Zé Baralho Mar 04 '20 at 15:42