Skip to content
Advertisement

How to map an array of objects in a a new array with new key value

I have a situation where I have an array of objects like this:

[
    {
        "name": "Phone call",
        "value": "Phone call"
    },
    {
        "name": "SMS",
        "value": "SMS"
    },
    {
        "name": "Email",
        "value": "Email"
    }
]

I have to remap the above OBJ to a new one containing its translation which is similar to this from React-intl: formatMessage(formatMessage(messages.emailOptionPlaceholder)

And the idea is as follow:

if (obj.name === 'Email') formatMessage(formatMessage(messages.emailOptionPlaceholder) else obj.name

so the new array should contain the right translation which will populate a dropdown menu.

I tried so far like this but without success:

field.options.map(o => {
        return [
          o.name === 'Email'
            ? formatMessage(messages.emailOptionPlaceholder)
            : o.name,
          o.name === 'Phone call'
            ? formatMessage(messages.phoneOptionPlaceholder)
            : o.name,
          o.name === 'SMS'
            ? formatMessage(messages.smsOptionPlaceholder)
            : o.name,
        ];
      });

This gives back 3 arrays instead of one with the values I need.

My goal is to have an array containing the formatMessage(...) output for the 3 elemnts inside the object as example of the output:

[{
  name: Phone call
  value: <-- Phone call translation from formatMessage --> 
 }
{
  name: Email
  value: <-- Email translation from formatMessage --> 
 }
{
  name: SMS
  value: <-- SMS call translation from formatMessage --> 
 }
]

I’m getting that OBJ from back-end and need to put the translation of corresponding name inside a drop down menu and was wondering what solution can be better.

Advertisement

Answer

I would do it something like this. (not tested)

const mappings = {
    'Email': messages.emailOptionPlaceholder,
    'Phone call': messages.phoneOptionPlaceholder,
    'SMS': messages.smsOptionPlaceholder
};

const mapped = field.options.map((obj) => {
    const key = mappings[obj.name]
    if (key) {
        return {
            ...obj,
            value: formatMessages(key)
        }
    } else {
        // no mapping for object name.
        // do something to handle it or just return obj
        return obj
    }
}

If you are only interested in the values you can do this.

const mappings = {
    'Email': messages.emailOptionPlaceholder,
    'Phone call': messages.phoneOptionPlaceholder,
    'SMS': messages.smsOptionPlaceholder
};

const mapped = field.options.map((obj) => {
    const key = mappings[obj.name]
    return formatMessages(key) || key //
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement