JS 修改集合中某一个字段的名称

发布时间 2023-03-28 10:19:35作者: 大瘦猴

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

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

现在,我们想要将 year 字段改为 publicationYear。你可以使用 map 方法和对象解构来实现这个目标:

1 const booksWithPublicationYear = books.map(({ year, ...rest }) => {
2   return { publicationYear: year, ...rest };
3 });
4 
5 console.log(booksWithPublicationYear);

这将返回以下结果:

1 [
2   { publicationYear: 1988, title: 'The Alchemist', author: 'Paulo Coelho', genre: 'Fiction', pages: 163 },
3   { publicationYear: 1960, title: 'To Kill a Mockingbird', author: 'Harper Lee', genre: 'Fiction', pages: 281 },
4   { publicationYear: 1949, title: '1984', author: 'George Orwell', genre: 'Science Fiction', pages: 328 },
5   { publicationYear: 1813, title: 'Pride and Prejudice', author: 'Jane Austen', genre: 'Romance', pages: 435 },
6   { publicationYear: 1925, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', genre: 'Fiction', pages: 180 }
7 ]

在这个例子中,我们使用对象解构来将 year 字段赋值给变量 year,并使用剩余参数将其余的字段存储在 rest 中。然后,我们返回一个新的对象,该对象包含了重新命名的 publicationYear 字段和剩余的字段。最后,booksWithPublicationYear 数组包含了更新的信息,以满足我们的需求。