首页 > 解决方案 > 我可以使用过滤器从对象数组中提取值吗?

问题描述

我有一个对象数组:

const books = [
  {
    title: 'Book',
    author: 'Name'
  },
  {
    title: 'Book2',
    author: 'Name2'
  }
];

我想使用filter方法将标题提取到一个数组中。到目前为止,我尝试了这个,但数组返回了 2 个原始对象:

const getTheTitles = function(array) {
   const filteredArray = array.filter(function(book) {
      return book.title;
   })
   return filteredArray;
}

我也试过这个,但它导致一个空数组(不知道为什么):

const getTheTitles = function(array) {
   const filteredArray = array.filter(function(book) {
      book.title;
   })
   return filteredArray;
}

我知道这可以使用 map 来完成。但我正在尝试使用过滤器来完成它。

标签: javascriptarraysfilter

解决方案


如果您想获取某些过滤书籍的标题,则可以通过链接mapto 来实现filter,如下所示:

let filteredBookTitles = books
  .filter(book => book.author === "Some Name")           // first filter (us any criteria here to select only the books you want)
  .map(book => book.title);                              // then get the titles of those filtered books

演示:

const books = [{ title: "Animal Farm", author: "George Orwell" }, { title: "Oliver Twist", author: "Charles Dickens" }, { title: "1984", author: "George Orwell" }];

let georgeOrwellBooks = books.filter(book => book.author === "George Orwell")
  .map(book => book.title);

console.log(georgeOrwellBooks);

或者通过使用 areduce来执行这两项操作,同时只循环一次数组,如下所示:

let filteredBookTitles = books.reduce((acc, book) => {   // for each book in the books array
  if(book.author === "Some Name") {                      // if the book matches the criteria
    acc.push(book.title);                                // add its title to the results array
  }

  return acc;
}, []);

演示:

const books = [{ title: "Animal Farm", author: "George Orwell" }, { title: "Oliver Twist", author: "Charles Dickens" }, { title: "1984", author: "George Orwell" }];

let georgeOrwellBooks = books.reduce((acc, book) => {
  if(book.author === "George Orwell") {
    acc.push(book.title);
  }

  return acc;
}, []);

console.log(georgeOrwellBooks);


推荐阅读