Nested collection filter with JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of nested objects like this −

const arr = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 2,
   legs:[{
      carrierName: 'SunExpress'
   },
   {
      carrierName: 'SunExpress'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];

We are required to write a JavaScript function that takes one such array as the first argument and a search query string as the second argument.

Our function should filter the array to contain only those objects whose "carrier name" property value is the same value specified by the second argument.

If for the above array, the second argument is "Pegasus". Then the output should look like −

const output = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];

Example

The code for this will be −

const arr = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 2,
   legs:[{
      carrierName: 'SunExpress'
   },
   {
      carrierName: 'SunExpress'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];
const keys = ['Pegasus'];
const filterByKeys = (arr = [], keys = []) => {
   const res = arr.filter(function(item) {
      const thisObj = this;
      return item.legs.some(leg => {
         return thisObj[leg.carrierName];
      });
   }, keys.reduce((acc, val) => {
      acc[val] = true;
      return acc;
   }, Object.create(null)));
   return res;
}
console.log(JSON.stringify(filterByKeys(arr, keys), undefined, 4));

Output

And the output in the console will be −

[
   {
      "id": 1,
      "legs": [
         {
            "carrierName": "Pegasus"
         }
      ]
   },
   {
      "id": 3,
      "legs": [
         {
            "carrierName": "Pegasus"
         },
         {
            "carrierName": "SunExpress"
         }
      ]
   }
]
raja
Published on 24-Nov-2020 14:57:58
Advertisements