What is the best way to convert:
JavaScript
x
2
1
user = ['Name:Marry', 'Age:24', 'Gender:Female']
2
to
JavaScript
1
2
1
user = { 'Name':'Marry', 'Age':'24', 'Gender':'Female' }
2
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.
JavaScript
1
7
1
const result = user.reduce((acc, curr) => {
2
const [key, value] = curr.split(':');
3
acc[key] = value;
4
5
return acc;
6
}, {});
7
Hope this helps.