3

I have this array of strings:

[ 
  'Back to Main Window: Retour à la fenêtre principale',
  'All Client Groups: Tous les groupes de clients',
  'Filter by Client: Filtrer par client' 
]

I would like to transform it into an object with key/value pairs like so:

{
   'Back to Main Window': 'Retour à la fenêtre principale',
   'All Client Groups': 'Tous les groupes de clients',
   'Filter by Client': 'Filtrer par client' 
}

I have to tried to use map() & split(), but I get this output instead:

const results = translations.map(translation => {
  const [key, value] = translation.split(':');

  return { key: value };
});

// results returns an "array" with the "key" word as key for all values :(
// [ { key: ' Retour à la fenêtre principale' },
//   { key: ' Tous les groupes de clients' },
//   { key: ' Filtrer par client' } ]
// 
2
  • 1
    All you needed was to use a computed property name in your return: return {[key]: value}; Commented Nov 1, 2021 at 23:06
  • Does this answer your question? Dynamic object property names? Commented Nov 1, 2021 at 23:07

2 Answers 2

4

map over the array and split each item by ': ', then use Object.fromEntries:

const arr = [ 
  'Back to Main Window: Retour à la fenêtre principale',
  'All Client Groups: Tous les groupes de clients',
  'Filter by Client: Filtrer par client' 
]


const res = Object.fromEntries(arr.map(e => e.split(": ")))

console.log(res)

Sign up to request clarification or add additional context in comments.

1 Comment

For anyone who wants an array of arrays instead of an object, just remove the Object.fromEntries part.
1

An alternative solution to @Spectric would be to use reduce, to transform your array to an object.

const arr = [ 
  'Back to Main Window: Retour à la fenêtre principale',
  'All Client Groups: Tous les groupes de clients',
  'Filter by Client: Filtrer par client' 
];

function transform(arr) {
  return arr.reduce((obj, line) => {
    const [key, value] = line.split(': ');
    obj[key] = value;
    return obj;
  }, {});
}

console.log(transform(arr));

Comments

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.