skip to Main Content

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

2

Answers


  1. 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);
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search