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

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

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

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 :

Breaking the problem into smaller pieces can help.

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 }, { role: "Son" }];

//compare a single "a" element against a single "b" criterion
function matchesThisCriterion(aObj,bCrit) {
    returnResult =  Object.keys(bCrit).every(bKey => {
    return aObj[bKey] == bCrit[bKey]
  });
  return returnResult;
}

//filter the items that match
let d= a.filter(
    aObj => {
    //determine if a single "a" element matches at least some of the "b" criteria
    return b.some(bCrit => {
        return matchesThisCriterion(aObj,bCrit)
    })
  }
);
console.log(d)
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