Sachin
Sachin

Reputation: 155

How to filter array within array using key multiple values?

const usersLanguageData = {
  transactionId: 6847655349501841000,
  count: 5,
  providerList: [
    {
      code:['US'],
      weekendOfficeHours: false
    },
    {
      code:['US','IND'],
      weekendOfficeHours: true
    },
    {
      code:['US','IND','AUS'],
      weekendOfficeHours: false
    },
    {
      code:[],
      weekendOfficeHours: false
    },
    {
      weekendOfficeHours: true
    }
  ]
};

let filterKeyName1 = ["code"];
let filterValue1 = ['IND','US'];
//let filterValue2 = ['US'];
let filteredProviderData = usersLanguageData.providerList.filter(function(e) {
  return filterKeyName1.every(function(a) {
      console.log(e[a])
      return filterValue1.includes(e[a]);
  });
});

console.log(filteredProviderData);

Here the code snippet displays the usersLanguageData into the object form. Here I want to filter the values with the key say for example here filterKeyName1 = ['code'] and filterValue1 = ['IND','US'] it will displays the 2nd and 3rd object into the usersLanguageData object. Same way there is filterValue2 which is into the commented line it will displays the 1st,2nd and 3rd object from the usersLanguageData.

Upvotes: 0

Views: 51

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36574

you should use every() again inside the function. And also make use to check that e[a] exists before using every() because one of your item doesnot have code key

const usersLanguageData = { transactionId: 6847655349501841000, count: 5, providerList: [ { code:['US'], weekendOfficeHours: false }, { code:['US','IND'], weekendOfficeHours: true }, { code:['US','IND','AUS'], weekendOfficeHours: false }, { code:[], weekendOfficeHours: false }, { weekendOfficeHours: true } ] };

let filterKeyName1 = ["code"];
let filterValue1 = ['IND','US'];
//let filterValue2 = ['US'];
let filteredProviderData = usersLanguageData.providerList.filter(function(e) {
  return filterKeyName1.every(function(a) {
      console.log(e[a])
      return e[a] && filterValue1.every(x => e[a].includes(x));
  });
});

console.log(filteredProviderData);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386604

You could filter with the value and against the object's property or an empty array.

const usersLanguageData = { transactionId: 6847655349501841000, count: 5, providerList: [{ code: ['US'], weekendOfficeHours: false }, { code: ['US','IND'], weekendOfficeHours: true }, { code: ['US','IND','AUS'], weekendOfficeHours: false }, { code: [], weekendOfficeHours: false }, { weekendOfficeHours: true }] };

let key = "code";
let values = ['IND','US'];
let result = usersLanguageData.providerList
    .filter(o => values.every(v => (o[key] || []).includes(v)));

console.log(result);

Upvotes: 0

Related Questions