Rahul Jain
Rahul Jain

Reputation: 39

How to filter array of objects using customized input as filters

Using a multi select dropdown where i have an array of objects where i want to filter it out based on user input such as

[{
        "ServiceArea": "NON-CIO",
        "ManagingDirector": "qwe",
        "Lead": "abc",
        "Manager": "xyz"
        "id":"1",
        "Designation":"COO"
    },
    {
        "ServiceArea": "NON-CIO",
        "ManagingDirector": "dfg",
        "Lead": "hgf",
        "Manager": "lkj"
        "id":"2",
        "Designation":"CTO"
    },
    {
        "ServiceArea": "NON-CIO",
        "ManagingDirector": "out",
        "Lead": "poi",
        "Manager": "uyt",
        "id":"43",
        "Designation":"COO"
    },
    {
        "ServiceArea": "4500-CIO",
        "ManagingDirector": "yhh",
        "Lead": "trr",
        "Manager": "nbb"
        "id":"403",
        "Designation":"CTO"
    }
]

Custom user input 1st time-

ServiceArea = ["NON-CIO"]

I should be getting first three records. Second time user inputs

ManagingDirector = ["dgf","qwe"]

Here i should be getting first two records. I am using this function but it seems to append the array not replace.

//airData is main array

array.forEach((item)=>{
 var name = this.airData.filter( el=>el.ManagingDirector == item );
 this.airData.push.apply(this.finalArr,name);
});

Upvotes: 1

Views: 89

Answers (1)

gog
gog

Reputation: 11347

Assuming a filters object like this

const data = [{ServiceArea:"NON-CIO",ManagingDirector:"qwe",Lead:"abc",Manager:"xyz"},{ServiceArea:"NON-CIO",ManagingDirector:"dfg",Lead:"hgf",Manager:"lkj"},{ServiceArea:"NON-CIO",ManagingDirector:"qwe",Lead:"poi",Manager:"uyt"},{ServiceArea:"4500-CIO",ManagingDirector:"yhh",Lead:"trr",Manager:"nbb"}];

const filters = {
  ServiceArea: ["NON-CIO"],
  ManagingDirector: ["dgf", "qwe"],
  Manager: []
}

const result = data.filter(e =>
  Object.entries(filters).every(([key, vals]) =>
    vals.length === 0 || vals.includes(e[key])))

console.log(result)

Upvotes: 2

Related Questions