Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to search an array of objects using another array of objects

I have an array of objects like this

[
  {
    "prop1": "value1",
    "prop2": "value1",
    "check": {
      "gender": ['male'],
      "office": ['London','New York']
    }
  },
  {
    "prop1": "value2",
    "prop2": "value2",
    "check": {
      "gender": ['female'],
      "office": ['Berlin', 'New York']
    }
  }
]

I want to search this array passing another object, that will be compared to the check property of the array. So, if I search using this object

{
  "office": ['New York']
}

I will get back both elements of the above array, but if I search using this one

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "gender": ['male'],
  "office": ['London']
}

this will return the first element only. I want also to be able to pass something like

{
  "gender": ['female'],
  "office": ['London', 'Berlin'] // <- 2 elements here
}

and get back the second element. I can check if the objects are the same but I don’t know how to do a partial search, how can I do that?

>Solution :

const data = [{"prop1": "value1", "prop2": "value1", "check": {"gender": ['male'], "office": ['London','New York'] } }, {"prop1": "value2", "prop2": "value2", "check": {"gender": ['female'], "office": ['Berlin', 'New York'] } } ];

const filters = {
  "office": ['Berlin']
}

const customFilter = (data, filters) => {
    const fKeys = Object.keys(filters);
    return data.filter(o =>
        fKeys.every(k => (
            filters[k].some(fVal =>
                o.check[k].includes(fVal)
            )
        ))
    );
};

// Without indentations
// return data.filter(o => fKeys.every(k => filters[k].some(fVal => o.check[k].includes(fVal))));


const result = customFilter(data, filters);
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading