3

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

1
  • "only contains a subset of the ~arrays~ object's properties" Commented May 14, 2019 at 13:29

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

You could take the entries and filter by the key/value pairs.

var customers = [{ Name: "John Doe", Age: 80, Hair: "Red", Gender: "Male" }],
    searchObject = { Hair: "Red", Gender: "Male" },
    search = Object.entries(searchObject),
    result = customers.filter(o => search.every(([k, v]) => o[k] === v));

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.