有了这个:
Observable.combineLatest(localArray.map((i) => {
return <Observable that returns $value> }))
.map((statuses) => {
return statuses.filter((status) => {
return status.$value === CONDITION
});
}).subscribe((eligible: any[]) => {
...
是否可以将订阅的结果映射回 localArray
?我想知道哪个合格
项目属于哪个localArray
条目...
感谢您的帮助。
我在某处读到,订单是用 combineLatest
保留的。但是,使用 forEach
直接映射到索引将不起作用,因为如果满足条件,则符合条件的
结果可能返回与 localArray
不同的长度)满足。
我始终可以删除 .map()
并在 subscribe
block 中进行过滤,这将使我能够循环 localArray
并直接使用 eligible
数据进行更新:例如 localArray.forEach((ai, i) => { ai.eligible = Qualified[i] })
...
最佳答案
首先,代码:
Observable
// Turn an array, promise, or iterable into an observable.
.from(localArray)
// Map values to inner observable, subscribe and emit in order.
.concatMap((arrayElement: any) => {
// Returning an observable that returns a value
return Observable.of(arrayElement);
})
// Emit only values that meet the provided condition.
.filter((value: any) => {
return value === 'Some condition';
})
// Reduces the values from source observable to a single value that's emitted when the source completes.
// If you need the current accumulated value on each emission, try scan - https://www.learnrxjs.io/operators/transformation/scan.html
// The second argument here is the seed, the initial value provided the first time reduce is called. (In this case, an empty array)
.reduce((filteredValue: any, accumulatedFilteredValues: any[]) =>{
accumulatedFilteredValues.push(filteredValue);
return accumulatedFilteredValues;
}, [])
.subscribe((filteredValueArray: any[]) => {
// Do something with the array of ordered, filtered values
});
首先,我创建了一个可观察对象,使用 from 发出 localArray
中的每个 arrayElement 。
当每个arrayElement
被发出时,我将arrayElement
映射到一个Observable,它将返回一些值
(在这种情况下,我只返回数组元素)。我正在使用concatMap因为它将订阅内部可观察对象并在完成后发出它们的值,按照它们发出的顺序。
我使用filter仅发出满足条件的值
。过滤器采用一个返回 true
或 false
的函数。如果返回 true
,则将发出值
。
最后,我使用 reduce收集 filteredValue
并将其添加到 accumulatedFilteredValues
数组中。 Reduce 将一个函数作为其第一个参数,并将一个可选种子作为其第二个参数。
传递给reduce的函数接收最近的发射(filteredValue)作为其第一个参数,并接收累积值作为第二个参数(空数组[])
将这些运算符应用于发出的值后,传递给 subscribe 的函数会接收一个数组,其中包含来自 localArray
的已过滤、有序项目。
learn-rxjs是一个优秀的 RxJS 资源,其中包含各种运算符的示例和描述。
如果您使用 RxJS >= 5.5,请考虑使用 pipeable operators反而。在这种情况下,代码看起来会更接近这样:
from(localArray).pipe(
concatMap((arrayElement: any) => {
return Observable.of(arrayElement);
}),
filter(value => {
return value === 'Some condition';
}),
reduce((filteredValue: any, accumulatedFilteredValues: any[]) => {
accumulatedFilteredValues.push(filteredValue);
return accumulatedFilteredValues;
}, [])
)
.subscribe((filteredValueArray: any[]) => {
// Do something with the array of ordered, filtered values
});
关于javascript - 将值从 mergeLatest 映射到 Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48724556/