Home > other >  How to split an array of strings & return a single object with key/value pairs
How to split an array of strings & return a single object with key/value pairs

Time:11-02

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' } ]
// 

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related