你可以使用js对象析构函数,但在分配给新对象之前修改一些值吗



我有以下代码,用于从api接收电影数据。现在,我想从返回的json文件中创建一个新对象,但只包含属性的一个子集,同时在将其分配给新对象之前修改一些现有的属性值,我目前正在做很长的工作,但有没有办法使用javascript/typescript对象解构语法来实现这个结果?

我想使用一些现有的属性,如titleoverview,但希望更改poster_path属性值(我在if语句后的前两行中设置了这些值(。我能以更简洁/高效的方式实现同样的结果吗?

movieCollection.results.forEach(
(movie: {
poster_path: string,
backdrop_path: string,
title: string,
overview: string,
release_date: string,
vote_average: number,
vote_count: number,
genre_ids: number[],
}) => {
if (movie.backdrop_path) {
//create paths for pictures
let poster_path = this.secureBaseURL + this.posterSizes[4] + movie.poster_path;
let backdrop_path = this.secureBaseURL + this.posterSizes[5] + movie.backdrop_path;
//create array object
movieArray.push({
poster_path: poster_path,
backdrop_path: backdrop_path,
title: movie.title,
overview: movie.overview,
release_date: movie.release_date,
vote_average: movie.vote_average,
vote_count: movie.vote_count,
genre_ids: movie.genre_ids,
styles: {},
});
}
});

我建议使用Spread语法来有效地获得相同的结果。它允许在期望零个或多个键值对(用于对象文字(的地方扩展对象表达式;这是新数组中的对象。

movieCollection.results.forEach(
(movie: {
poster_path: string,
backdrop_path: string,
title: string,
overview: string,
release_date: string,
vote_average: number,
vote_count: number,
genre_ids: number[],
}) => {
if (movie.backdrop_path) {
//create array object
movieArray.push({
...movie, // keep the unchanged properties
poster_path: this.secureBaseURL + this.posterSizes[4] + movie.poster_path,
backdrop_path: this.secureBaseURL + this.posterSizes[5] + movie.backdrop_path, // override these two properties as needed
styles: {},
});
}
});

然而,我注意到,您在这里想要做的似乎是更改数组中的对象,并将更新后的结果保留在另一个数组中?然后,实际上,您可以使用数组映射来更简洁地重构代码。

const movieArray = movieCollection.results
.filter((t) => !!t.backdrop_path) // filter by backdrop_path property
.map(
(movie) => ({
...movie, // keep the unchanged properties
poster_path: this.secureBaseURL + this.posterSizes[4] + movie.poster_path,
backdrop_path: this.secureBaseURL + this.posterSizes[5] + movie.backdrop_path,
styles: {},
}),
);

最新更新