JavaScript uses an array to filter another array of objects
Suppose we have an array of objects objs
, each of which has a name
property, and we want to use an array names
to objs
filter the array and keep only those objects whose name
property is in names
the array. We can use filter()
the method to achieve this functionality.
const objs = [
{
id: 1, name: "Alice" },
{
id: 2, name: "Bob" },
{
id: 3, name: "Charlie" },
{
id: 4, name: "David" },
];
const names = ["Alice", "Charlie"];
const filteredObjs = objs.filter((obj) => names.includes(obj.name));
console.log(filteredObjs);
// Output: [{id: 1, name: 'Alice'}, {id: 3, name: 'Charlie'}]
In the above example, we use filter()
the method to objs
filter the array, filter out those objects name
whose property names
is in the array, and store the result in filteredObjs
the array. Here we use includes()
the method to check names
whether the array contains name
the property of the current object.
Using this method, we can conveniently filter an object array, and define filter conditions through any array to achieve more flexible filtering functions.