Filter object from array based on multiple nested values

Basically I’m trying to figure out the cleanest way to select one item from an array, only if all certain values exist.

const filterValues = ['blue', '30cm', 'true'];

const products = [
{
  details: [
    { id: 1, value: 'red' },
    { id: 2, value: '30cm' },
    { id: 3, value: 'true' },
    { id: 4, value: '123432'}
  ],
  name: "Product 1"
},
{
  details: [
    { id: 5, value: 'blue' },
    { id: 6, value: '30cm' },
    { id: 7, value: 'true' },
    { id: 8, value: '98348'}
  ],
  name: "Product 2"
},
{
  details: [
    { id: 9, value: 'black' },
    { id: 10, value: '40cm' },
    { id: 11, value: 'false' },
    { id: 12, value: '578347'}
  ],
  name: "Product 3"
},
]

Only Product 2 contains all the filter values, so I want to return that product.

I have tried:

products.filter(p => {
  p.details.find(k => filterValues.includes(k.value));
})

but this returns if any of the values satisfies the condition rather than if all of them are included. This is the main issue here. I’m struggling with finding a way to filter if only all these values int he array are present in the object.

98 thoughts on “Filter object from array based on multiple nested values”

Leave a Comment