JS 提取集合中的部分字段到新的集合

假设你有一个包含以下数据的集合:

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 数组中提取出来的信息,以满足我们的需求。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章