I am working with an array of objects called c
, which looks like this:
c = [
{
name: 'abc',
category: 'cat1',
profitc: 'profit1',
costc: 'cost1'
},
{
name: 'xyz',
category: '',
profitc: 'profit1',
costc: ''
},
{
name: 'pqr',
category: 'cat1',
profitc: 'profit1',
costc: ''
}
]
I need to filter this array based on another array of objects called arr
:
arr = [
{
type:'profitc'
value: 'profit1',
},
{
type:'category'
value: 'cat1',
}
]
The user selects values from this array using a dropdown with multiple select options. If a user selects profit1
and cat1
, the filtered output should look like this:
c = [
{
name: 'abc',
category: 'cat1',
profitc: 'profit1',
costc: 'cost1'
},
{
name: 'pqr',
category: 'cat1',
profitc: 'profit1',
costc: ''
}
]
I attempted to filter the array using the code below, but it returned all objects from the c
array. Can you suggest what I might be doing wrong and if there is a way to achieve this using lodash?
let result = c.filter(e => {
let istruecat = true
//arr is chosen value from the user.
arr.forEach(element => {
istruecat = e[element.type] == element.value;
})
return istruecat;
})