user2024080
user2024080

Reputation: 5101

How to filter the array of object by matching all values instead of one

I am implementing a filter. it works fine. the problem is it's just matching a single object value instead of all value matching.

Matching means here is, let it be contain any single letter in the value

example: here is my object

{name:"D",color:"Green",size:50}

in case if i pass the filter object as :

let filter1 = {color:"Blu",size:'50'};

at present I am getting single result by matching size. But the color is not matching at all. so the result should be empty.

How to mach all values in the object and get the filtered value.

Live Demo

Code :

const nestedFilter = (targetArray, filters) => targetArray.filter(o => Object.keys(filters).find(k => filters[k].includes(o[k])));

let products = [
  {name:"A",color:"Blue",size:70},
  {name:"B",color:"Blue",size:60},
  {name:"C",color:"Black",size:70},
  {name:"D",color:"Green",size:50}
];

let filter1 = {color:"Blu",size:'50'};


console.log(nestedFilter(products, filter1));

Upvotes: 0

Views: 69

Answers (2)

trincot
trincot

Reputation: 350705

Replace the .find invocation with .every. Be aware though that by using includes you expect your property values to be String.

If you want includes to work to other way round, so that the filter value can be a substring of the data, you should do:

const nestedFilter = (targetArray, filters) => 
    targetArray.filter(o => Object.keys(filters).every(k =>
        String(o[k]).includes(filters[k]))
    )
)

The o[k] value needs to be converted to string, as otherwise you cannot apply includes to it (cf. size which is a number)

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370979

Check whether every of the Object.entries of the filter passed is equal to the same entry on the object being iterated over. If you want partial matches and are using different types of variables, it sounds like you also need to coerce them to strings first, so you can use .includes.

const nestedFilter = (targetArray, filters) => targetArray.filter(
  obj => Object.entries(filters).every(
    ([key, val]) => String(obj[key]).includes(val)
  )
);

let products = [
  {name:"A",color:"Blue",size:70},
  {name:"B",color:"Blue",size:60},
  {name:"C",color:"Black",size:70},
  {name:"D",color:"Green",size:50},
  {name:"E",color:"Blu",size:'50'}
];

let filter1 = {color:"Blu",size:'70'};


console.log(nestedFilter(products, filter1));

Upvotes: 0

Related Questions