search for all the objects in a list using all its properties

Advertisements

I have list of objects in my application

[
{id: 97, name: 'create', obeName: 'None', version: '5.1', versionNum: 5.1, …}

{id: 7, name: 'fare', obeName: 'None', version: '7.3', versionNum: 7.3, …}

{id: 1324, name: 'serach_flyer', obeName: 'None', version: '9.1', versionNum: 9.1, …}

{id: 24, name: 'PNR_AddFrequentFlyer', obeName: 'None', version: '12.1', versionNum: 12.1, …}

{id: 14, name: 'price booking', obeName: 'Availability', version: '18.1', versionNum: 18.1, …}

{id: 2644, name: 'downline', obeName: 'None', version: '2.7', versionNum: 2.7, …}

{id: 235921, name: 'airline service', obeName: 'None', version: '1.0', versionNum: 1, …}]

I have to filter this data according to the object given below

ob = {name: 'airline', version: '1.4'}

how to do this, I am trying with .filter() method in javascript(angular)

I tried with

list.filter(
        data => {
          for (var prop in ob) {
            if (Object.prototype.hasOwnProperty.call(ob, prop)) {
              if( typeof ob[prop] === 'string'){
                ob[prop].toLowerCase().includes(data[prop].toLowerCase())
              }
              else{
                  ob[prop].includes(data[prop])}
}})

>Solution :

Here’s a solution that, for every property in your search object:

  • Compares if the (lower-cased) search string is contained in the corresponding data value for string types.
  • Compares if the search value and data value are equal for other types.
const list = [
  {id: 97, name: 'create', obeName: 'None', version: '5.1', versionNum: 5.1, },
  {id: 7, name: 'fare', obeName: 'None', version: '7.3', versionNum: 7.3, },
  {id: 1324, name: 'serach_flyer', obeName: 'None', version: '9.1', versionNum: 9.1, },
  {id: 24, name: 'PNR_AddFrequentFlyer', obeName: 'None', version: '12.1', versionNum: 12.1, },
  {id: 14, name: 'price booking', obeName: 'Availability', version: '18.1', versionNum: 18.1, },
  {id: 2644, name: 'downline', obeName: 'None', version: '2.7', versionNum: 2.7, },
  {id: 235921, name: 'airline service', obeName: 'None', version: '1.0', versionNum: 1, },
];

const ob = {name: 'airline', version: '1.0'};


const result = list.filter(data => Object.entries(ob).every(
  ([k, v]) => typeof v === 'string'
                ? data[k].toLowerCase().includes(v.toLowerCase())
                : data[k] === v
));

console.log(result);

Leave a Reply Cancel reply