-1

I am using the instant method from ngx-translate to translate some messages into the language of the user. These messages are passed as JSON to ngx-translate. Some of the messages take dynamic values:

{
"message.key": "First value is {{0}} and second value is {{1}}",
"message.key2": "Value is {{0}}" 
}

To get the translated text with the interpolated dynamic values, I use the instant method like this messageText = this.translateService.instant('message.key2', {0: 'Value to be interpolated'});

The problem is that I get these values in a string array params: string[]. So I need to transform the string array into an Object that looks like {0:params[0], 1:params[1]}
I know that I could use a construct like

myTranslationMethod(messageKey: string, params: string[]): string {
  let paramsAsObject;
  if (params.length === 1) {
    paramsAsObject = {
      0: params[0]  
    }
  } else {
    paramsAsObject = {
      0: params[0],
      1: params[1]
    }
  }
  messageText = this.translateService.instant(messageKey,paramsAsObject);
  return messageText; 
}

However, I would need to extend the if construct if a message with three or more parameters is added to the application. So I want to implement it in a generic way, where I don't need to change the code if a message with more parameters is used.

Is there a way to create paramsAsObject independent of the length of params or to use the array directly with ngx-translate?

Thank you for your input.

stm
  • 174
  • 1
  • 2
  • 11
  • It's difficult to follow the question tbh – Drenai Mar 21 '22 at 20:50
  • I edited the question and tried to make it easier to follow – stm Mar 21 '22 at 21:40
  • Sorry, my bad. The different translations are stored in property files. So the first code block was meant to represent an excerpt of a properties file. However, the properties files are transformed to json before the content is passed to ngx-translate. So the instant method only gets the key that is used to retrieve the corresponding message. – stm Mar 21 '22 at 22:28

1 Answers1

1

If I understand this correctly you basically want obj paramsAsObject to be constructed automatically when params[] is supplied.

myTranslationMethod('', ['1', 'test', 'something']);

function myTranslationMethod(messageKey, params) {
  let paramsAsObject = {};
  for (let i = 0; i < params.length; i++) {
    Object.assign(paramsAsObject, {
      [i]: params[i]
    });
  }
  console.log(paramsAsObject);
}

// {0: "1", 1: "test", 2: "something"}
Joosep Parts
  • 5,372
  • 2
  • 8
  • 33