Reputation: 85
I have the following piece of string: 'username=Tomas&password=123', I've tried to split the string into 2 parts then split it again to remove the equals sign but don't know how to load that into a dictionary
Upvotes: 0
Views: 61
Reputation: 92440
Once you've split the components, you can split again inside reduce()
and assign to the object. You could also do this in a for
loop if you don't want to use reduce()
.
let str = 'username=Tomas&password=123'
let components = str.split('&') // [ 'username=Tomas', 'password=123' ]
let dict = components.reduce((obj, comp) => {
let [key, val] = comp.split('=') // ['username', 'Tomas']
obj[key] = val
return obj
}, {})
console.log(dict)
Upvotes: 1