【发布时间】:2020-11-05 00:59:11
【问题描述】:
所以我有一个来自 api 的返回对象,其结构如下:
{
status: 'ok',
stuff: [array of objs],
page: xyz
}
我正在使用“pluck”运算符来提取属性“stuff”。但是,我需要在它上面运行一个 map 运算符,并为返回的 stuff 对象数组中的每个对象添加一个新属性。到目前为止,我的 map 运算符正在将属性添加到数组的末尾(而不是添加到每个对象)。想知道我哪里错了。
this.blogsFromAPI$ =
this.blogService
.getBlogs()
.pipe(
pluck('stuff'),
map(st => {
st.url = "myurl" + st.alias;
console.log(st );
})
);
}
然后,我想按日期时间按最近的顺序对数组进行排序。像这样的:
// this.blogsFromAPI$ = this.blogService.getBlogs().pipe(
// pluck('articles'),
// map(articles => articles.map(a => {
// // take articles array from return object, loop over them,
// // construct redirect url & return a new obj with the new property
// a.url = "http://globalfinancialdata.com/" + a.alias;
// return a;
// }), map(art => art.sort((a, b) => new Date(b.published_at).getTime() - new Date(a.published_at).getTime())))
// );
【问题讨论】:
-
stuff 是一个数组,你可能需要遍历每个元素才能得到你想要的结果
-
但 map 无法在“stuff”中的每个元素上运行代码并进行这些更改。是为了数据转换,对吧?
-
附带说明,改变值是一种副作用,并且惯用的操作是点击,而不是映射。