简体   繁体   English

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

[英]Can I use filter to extract values from an array of objects?

I have an array of objects:我有一个对象数组:

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

I'd like to extract the titles into an array using the filter method.我想使用filter方法将标题提取到一个数组中。 So far I tried this but the array returns with the 2 original objects:到目前为止,我尝试过这个,但数组返回了 2 个原始对象:

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

I also tried this but it results in an empty array (not sure why):我也试过这个,但结果是一个空数组(不知道为什么):

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

I understand that this could be accomplished using map.我知道这可以使用 map 来完成。 But I am trying to accomplish it using filter.但我正在尝试使用过滤器来完成它。

If you want to get the titles of certain filtered books, then either do it by chaining map to filter , like so:如果您想获取某些已过滤书籍的标题,则可以通过将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

Demo:演示:

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

Or by using a reduce to do both while looping the array only once, like so:或者通过使用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;
}, []);

Demo:演示:

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

You can only use Array#filter to remove items but not to transform them.您只能使用Array#filter删除项目但不能转换它们。 The filter function is applied to each item.过滤功能应用于每个项目。 If the function returns true (or anything that is truthy ) the item is kept otherwise it is removed.如果函数返回true (或任何为truthy)项目保持否则将被删除。

Example: keeping only odd numbers:示例:只保留奇数:

[1,2,3,4,5].filter(n => n % 2 !== 0);
//=> [1,3,5]

Example: removing false from an array of booleans:示例:从布尔数组中删除false

[true,false,true,false].filter(b => b);
//=> [true,true]

What you're trying to do is to transform all items.您要做的是转换所有项目。 eg from [{n:1},{n:2},{n:3}] to [1,2,3] .例如从[{n:1},{n:2},{n:3}][1,2,3] In this case you need Array#map which applies a function to all items and creates a new array with the results:在这种情况下,您需要Array#map将函数应用于所有项目并创建一个包含结果的新数组:

[{n:1},{n:2},{n:3}].map(o => o.n);
//=> [1,2,3]

Why does this function return all books?为什么这个函数返回所有书籍?

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

The problem is that your filter function evaluates book.title to decide whether to keep the book object.问题在于您的过滤器函数会评估book.title以决定是否保留 book 对象。 However all your books have a title and therefore this function is the same as saying "Does this book have a title?"然而,你所有的书都有一个标题,因此这个功能与说“这本书有标题吗?”是一样的。

Why does this function return no books at all?为什么这个函数根本不返回书?

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

The problem is that your filter function doesn't actually return anything explicitly .问题是您的过滤器函数实际上并没有显式返回任何内容 When a function has no return statement then it returns undefined by default which is a "falsy" value.当一个函数没有return语句时,它默认返回undefined ,这是一个“假”值。 This function is the same as saying "Ignore all books"此功能与说“忽略所有书籍”相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM