我有一些来自服务器的选项
const options = [
{key: 1, label: 'label1'},
{key: 2, label: 'label2'},
{key: 3, label: 'label3'},
{key: 4, label: 'label4'},
{key: 5, label: 'label5'},
{key: 6, label: 'label6'},
];
我需要的是根据每个数组项的key
映射翻译并返回翻译后的选项数组
const options = [
{key: "key1", label: 'label1', translated: 'translation 1'},
{key: "key2", label: 'label2', translated: 'translation 2'},
{key: "key3", label: 'label3', translated: 'translation 3'},
{key: "key4", label: 'label4', translated: 'translation 4'},
{key: "key5", label: 'label5', translated: 'translation 5'},
{key: "key6", label: 'label6', translated: 'translation 6'},
];
我设法使用from(options)
来做到这一点,但是显然它会单独发出数组的每个成员-我需要完整的数组。在下面的代码中,我尝试压缩所有翻译,但仅收到翻译后的字符串数组-如何将它们映射回每个option
?
import { of, from, timer, zip } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
const getTranslation = (key) => of('translation ' + key)
const options = [
{ key: "key1", label: 'label1' },
{ key: "key2", label: 'label2' },
{ key: "key3", label: 'label3' },
{ key: "key4", label: 'label4' },
{ key: "key5", label: 'label5' },
{ key: "key6", label: 'label6' },
];
of(options).pipe(
mergeMap(options =>
zip(...options.map(option =>
getTranslation(option.key)))
)).subscribe(console.log);
在这里我创建了playground on stackblitz
答案 0 :(得分:2)
您可以将每个选项映射到一个Observable,然后forkJoin将它们全部加入:
forkJoin(options.map(options =>
getTranslation(option.key).pipe(map(translation => ({
...option,
translated: translation
})))
)).subscribe(console.log);
答案 1 :(得分:0)
使用传播和休息(...
)收集对象,然后重新传播其余对象:
zip(...options.map(({ key, ...option }) => ({ ...option, key: getTranslation(key) })))