-1

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

1
  • It looks like you need at least one of the criteria in b to match an item a. In your filter, you need to somehow iterate through all the items in b and see if it matches something in `a. Commented Oct 11, 2024 at 19:41

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.