假設你有一個包含以下數據的集合:
1 const books = [ 2 { title: 'The Alchemist', author: 'Paulo Coelho', year: 1988, genre: 'Fiction', pages: 163 }, 3 { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960, genre: 'Fiction', pages: 281 }, 4 { title: '1984', author: 'George Orwell', year: 1949, genre: 'Science Fiction', pages: 328 }, 5 { title: 'Pride and Prejudice', author: 'Jane Austen', year: 1813, genre: 'Romance', pages: 435 }, 6 { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', year: 1925, genre: 'Fiction', pages: 180 } 7 ];
現在,我們想要從每個書籍對象中提取 title
和 author
字段,創建一個新的集合只包含這些字段。你可以使用 map
方法來實現這個目標:
1 const titlesAndAuthors = books.map(book => { 2 return { title: book.title, author: book.author }; 3 }); 4 5 console.log(titlesAndAuthors);
這將返回以下結果:
1 [ 2 { title: 'The Alchemist', author: 'Paulo Coelho' }, 3 { title: 'To Kill a Mockingbird', author: 'Harper Lee' }, 4 { title: '1984', author: 'George Orwell' }, 5 { title: 'Pride and Prejudice', author: 'Jane Austen' }, 6 { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' } 7 ]
在這個例子中,map
方法將對 books
數組中的每個元素執行一個函數,該函數返回一個新的對象,只包含 title
和 author
字段。最後,titlesAndAuthors
數組包含了從原來的 books
數組中提取出來的信息,以滿足我們的需求。