Skip to content
Advertisement

Javascript: How to convert array [“a=1”, “b=2”] into an object? [closed]

What is the best way to convert:

user = ['Name:Marry', 'Age:24', 'Gender:Female']

to

user = { 'Name':'Marry', 'Age':'24', 'Gender':'Female' }

Advertisement

Answer

Here you want to convert an array to a single value( here it is an object ), for this more declarative way is to use reduce method. Here I have given an empty object as the initial value of the accumulator and on each iteration it adds the key value pair.

const result = user.reduce((acc, curr) => {
  const [key, value] = curr.split(':');
  acc[key] = value;
  
  return acc;
}, {});

Hope this helps.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement