Home > Enterprise >  How to search an array of objects using another array of objects
How to search an array of objects using another array of objects

Time:02-03

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

{
  "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?

CodePudding user response:

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);

CodePudding user response:

   function searchArray(array, searchObj) {
  return array.filter(element => {
    return Object.entries(searchObj).every(([key, value]) => {
      return element.check[key] && element.check[key].includes(value[0]);
    });
  });
}

This function uses the filter method to iterate over the array of objects and the Object.entries method iterates over the properties in the search object. For each property in the search object, the function checks if it exists in the check property of the current array object and if its value includes the value from the search object.

CodePudding user response:

const searchIn = (data, search) => data.filter(value => {
  const arr = Object.entries(search).filter(([key, data]) => {
    return value.check[key].some(a => data.includes(a))
  })
  return arr.length
})
  • Related