0

I have array of options that is coming from server

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

what I need is to map each array item with translation based on its key and return array of translated options

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

I managed to do this using from(options) but it obviously emits each member of array separatelly - I need full array instead. In the code below I'm tryingtried to zip all translations, but I receive array of translated strings only - how do I map them back into each 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);

here I created playground on stackblitz

2 Answers 2

2

You could map each option to an Observable and then forkJoin them all:

forkJoin(options.map(options =>
  getTranslation(option.key).pipe(map(translation => ({
    ...option,
    translated: translation
  })))
)).subscribe(console.log);
Sign up to request clarification or add additional context in comments.

1 Comment

yeah this works even with mapMerge - the key to solving was passing getTranslation() result to pipe(map(translation => {...})), tyvm!
-1

Use spread and rest (...) to collect and then re-spread the rest of the object:

zip(...options.map(({ key, ...option }) => ({ ...option, key: getTranslation(key) })))

1 Comment

this will pass multiple {...option, key: getTranslatedKey()} objects while zip expects multiple Observables as input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.