javascriptlist

Using Javascript, filter between 2 list of objects but the condition to be dynamic


I have 2 list of objects. One is the data and the other is the include conditions. I would want to device a filter in such a way that if the list that include conditions, has more properties added, it should still work.

const a = [{name:'John',age:38,role:'Dad'},{name:'Jane',age:38,role:'Mom'},{name:'Patricia',age:11,role:'Daughter'},{name:'Mike',age:6,role:'Son'}]
const b = [{age:38}]

let d = a.filter( (x) => {
  if (b.some( (y) => 
     y.age == x.age )  ) {
        return true
     } else return false
})
console.log(d)


Above code will give me

[{name:'John',age:38,role:'Dad'},{name:'Jane',age:38,role:'Mom'}]

but if i add another criteria to variable b

const b = [{age:38}, {role:'Son'}]

I need the result to be

[{name:'John',age:38,role:'Dad'},{name:'Jane',age:38,role:'Mom'},{name:'Mike',age:6,role:'Son'}]

The include condition can keep growing. Is it possible to device a filter condition to handle this?

Thanks Sikkandhar


Solution

  • You were close to the right solution. You can use Object.keys() to get the name of the key in the condition object. Now compare the value of the list with the value of the condition.

    const list = [{name:'John',age:38,role:'Dad'},{name:'Jane',age:38,role:'Mom'},{name:'Patricia',age:11,role:'Daughter'},{name:'Mike',age:6,role:'Son'}];
    const conditions = [{age:38}, {role:'Son'}];
    const result = list.filter(item => conditions.some(condition => {
      const [key] = Object.keys(condition);
      return item[key] === condition[key];
    }));
    console.log(result);