RBG
RBG

Reputation: 91

Filter array of objects where one field in object is array

 data:[
        {
           id:1,
           tags:['TagA','TagB','TagC']
         },
         {
           id:2,
           tags:['TagB','TagD']
         },
         {
            id:3,
            tags:['tagE','tagC']
         }
      ]

filterCondition:{tags:['TagA','TagB']}

Expected Output: [
                   {
                     id:1,
                     tags:['TagA','TagB','TagC']
                   },
                   {
                     id:2,
                     tags:['TagB','TagD']
                   }
                 ]

Is there a possible way to achieve this in typescript using filter method? It is possible when tags field is not an array but when it is in array the code breaks.

I tried but it fails:

   data.filter(o => Object.keys(filterCondition).every(k => filterCondition[k].some(f => o[k] === f)));

Upvotes: 4

Views: 940

Answers (2)

Muni Kumar Gundu
Muni Kumar Gundu

Reputation: 532

const s = {
  data: [{
      id: 1,
      tags: ['TagA', 'TagB', 'TagC']
    },
    {
      id: 2,
      tags: ['TagB', 'TagD']
    },
    {
      id: 3,
      tags: ['tagE', 'tagC']
    }
  ],
  filterCondition: {
    tags: ['TagA', 'TagB']
  }
};

console.log(s.data.filter(a => s.filterCondition.tags

  .some(s => a.tags.join(',').includes(s))));

Upvotes: 2

Artyom Amiryan
Artyom Amiryan

Reputation: 2966

you can use filter and includes

const data = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];
      
const filterData = tag => data.filter(d => tag.some(t => d.tags.includes(t)));

console.log(filterData(['TagA', 'TagB']));

Little edit in the form of conditionArray mentioned:

    let filterArray={tags:['TagA','TagB']}

    const data = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];

    output= data.filter(o => Object.keys(filterArray).every(d => filterArray[d].some(t => o[d].includes(t))));

Upvotes: 3

Related Questions