Home > Article > Web Front-end > How can I filter an array of objects based on matching properties in another array?
Filtering Array of Objects with Another Array of Objects
This problem involves filtering an array of objects (myArray) using an array of objects (myFilter). The objective is to create a new array (myArrayFiltered) that contains only the elements in myArray that match the corresponding elements in myFilter based on userid and projectid.
Consider the following example:
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" } ]; myFilter = [ { userid: "101", projectid: "11" }, { userid: "102", projectid: "12" }, { userid: "103", projectid: "11" } ];
The expected result is:
myArrayFiltered = [ { userid: "101", projectid: "11", rowid: "1" }, { userid: "102", projectid: "12", rowid: "2" } ];
To accomplish this task, we can employ the filter and some array methods. These methods are widely available in modern browsers, and polyfills exist for older browsers.
The implementation involves filtering myArray using the filter method, where each element of myFilter is used to compare against the elements of myArray. The some method is then employed to check if there is at least one match between the userid and projectid properties of the current element in myArray and the corresponding element in myFilter. If there is a match, the current element is included in the filtered result.
Here's an example code snippet that demonstrates this approach:
<code class="javascript">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; }); }); console.log(myArrayFiltered);</code>
This code will output the expected result, providing a filtered array containing only the objects from myArray that match the criteria specified in myFilter.
The above is the detailed content of How can I filter an array of objects based on matching properties in another array?. For more information, please follow other related articles on the PHP Chinese website!