JavaScript uses an array to filter another array of objects

JavaScript uses an array to filter another array of objects

Suppose we have an array of objects objs, each of which has a nameproperty, and we want to use an array namesto objsfilter the array and keep only those objects whose nameproperty is in namesthe 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 objsfilter the array, filter out those objects namewhose property namesis in the array, and store the result in filteredObjsthe array. Here we use includes()the method to check nameswhether the array contains namethe 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.

Guess you like

Origin blog.csdn.net/yzh648542313/article/details/130751782