gpt4 book ai didi

javascript - RxJS 将数组与另一个可观察量映射并返回数组

转载 作者:行者123 更新时间:2023-12-02 23:20:09 25 4
gpt4 key购买 nike

我有来自服务器的一系列选项

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'},
];

我需要的是根据其将每个数组项与翻译进行映射,并返回翻译选项数组

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) 来做到这一点,但它显然单独发出数组的每个成员 - 我需要完整的数组。在下面的代码中,我尝试压缩所有翻译,但我只收到翻译后的字符串数组 - 如何将它们映射回每个选项

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

最佳答案

您可以将每个选项映射到一个 Observable,然后 forkJoin 所有选项:

forkJoin(options.map(options =>
getTranslation(option.key).pipe(map(translation => ({
...option,
translated: translation
})))
)).subscribe(console.log);

关于javascript - RxJS 将数组与另一个可观察量映射并返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56985796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com