To filter array of objects with another array of objects with JavaScript, we use the filter
method.
For instance, we write
const myArray = [
{ userid: "100", projectid: "10", rowid: "0" },
{ userid: "101", projectid: "11", rowid: "1" },
{ userid: "102", projectid: "12", rowid: "2" },
{ userid: "103", projectid: "13", rowid: "3" },
{ userid: "101", projectid: "10", rowid: "4" },
];
const myFilter = [
{ userid: "101", projectid: "11" },
{ userid: "102", projectid: "12" },
{ userid: "103", projectid: "11" },
];
const myArrayFiltered = myArray.filter((el) => {
return myFilter.some((f) => {
return f.userid === el.userid && f.projectid === el.projectid;
});
});
to call myArray.filter
with a callback that checks if the properties of object el
in myArray
has the userid
and projectid
equal to object f
in myFilter
with some
.
Then the items in myArray
that matches any object property we check for in myFilter
is returned.