Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a javascript array by an object only containing a subset of the array properties

I have an array of objects that have many properties. I would like to be able to find the matching items, based on a filter object that only contains a subset of the arrays properties. For Example, i have a customer

let Customer = {
    Name: "John Doe",
    Age: 80,
    Hair: "Red",
    Gender: "Male",

};

And i have my search object:

let searchObject ={
    Hair: "Red",
    Gender: "Male"
}

I want to be able to find inside my array, all customers that match searchObject, without having to do:

this.array.filter(z=>z.Hair == searchObject.Hair && z.Gender == searchObject.Gender);

I would like for it to be when searchObject adds more properties, it automatically filters on those too

like image 377
scarson Avatar asked Aug 09 '26 22:08

scarson


1 Answers

You can use every() on Object.keys() of searchObject inside and check if all the values of keys in searchObject matches with corresponding values of object in array.

Below in the snippet I have two object with different Gender

let array = [{
    Name: "John Doe",
    Age: 80,
    Hair: "Red",
    Gender: "Male",
},{
    Name: "Marry",
    Age: 80,
    Hair: "Red",
    Gender: "Female",
}]

let searchObject ={
    Hair: "Red",
    Gender: "Male"
}

const res = array.filter(x => Object.keys(searchObject).every(k => x[k] === searchObject[k]));

console.log(res)
like image 110
Maheer Ali Avatar answered Aug 13 '26 11:08

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!