Reputation: 1226
I have an array:
const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ]
And I want to convert it to an object like this:
const obj = { name: 'Jon', weapon: 'sword', hair: 'shaggy' }
I've tried splitting the array by the =
to get the key
and value
and then mapping the new array and sending those values to an empty object but it doesn't get the right key
const split = arr.map( el => el.split('=') )
let obj = {};
split.map( el => {
const key = el[0];
const val = el[1];
obj.key = val;
}
)
obj
returns as {key: 'shaggy'}
Upvotes: 1
Views: 66
Reputation: 37755
You can use Object.fromEntries
const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ]
const obj = Object.fromEntries(arr.map(v => v.split('=')))
console.log(obj)
Upvotes: 3
Reputation: 370679
Generally, to convert an array into an object, the most appropriate method to use is .reduce
:
const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ];
const obj = arr.reduce((a, str) => {
const [key, val] = str.split('=');
a[key] = val;
return a;
}, {});
console.log(obj);
You should only use .map
when you need to create a new array by carrying out an operation on every item in the old array, which is not the case here.
Upvotes: 4