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'}
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.