javascript - 我可以使用过滤器从对象数组中提取值吗?

标签 javascript arrays filter

我有一个对象数组:

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 来完成。但我正在尝试使用过滤器来完成它。

最佳答案

如果你想获得某些过滤书籍的标题,那么要么通过将 map 链接到 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);

或者通过使用 reduce 来完成这两项操作,同时仅循环数组一次,如下所示:

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);

关于javascript - 我可以使用过滤器从对象数组中提取值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64635476/

相关文章:

symfony - 如何使用symfony2.0设置默认选中filter_checkbox选择字段?

javascript - 按值合并数组中的对象并获取每个对象的计数

javascript - 即使使用 `Cache-Control: max-age`,浏览器是否继续发送资源请求

jquery - 使用jquery过滤图像src中的单词

带有过滤器的Scala Future以进行理解

c++ - 在 C++ 中正确定义和返回函数数组

javascript - 不变违规 : Element type is invalid:

javascript - 从带参数的指令调用 Controller 函数

c# - 如何获得多个数组的所有组合?

javascript - 如何从拆分数组函数中乘以数据