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