簡體   English   中英

我可以使用過濾器從對象數組中提取值嗎?

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

我有一個對象數組:

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

您只能使用Array#filter刪除項目但不能轉換它們。 過濾功能應用於每個項目。 如果函數返回true (或任何為truthy)項目保持否則將被刪除。

示例:只保留奇數:

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

示例:從布爾數組中刪除false

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

您要做的是轉換所有項目。 例如從[{n:1},{n:2},{n:3}][1,2,3] 在這種情況下,您需要Array#map將函數應用於所有項目並創建一個包含結果的新數組:

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

為什么這個函數返回所有書籍?

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

問題在於您的過濾器函數會評估book.title以決定是否保留 book 對象。 然而,你所有的書都有一個標題,因此這個功能與說“這本書有標題嗎?”是一樣的。

為什么這個函數根本不返回書?

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

問題是您的過濾器函數實際上並沒有顯式返回任何內容 當一個函數沒有return語句時,它默認返回undefined ,這是一個“假”值。 此功能與說“忽略所有書籍”相同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM