0

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

  • Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – NineBerry Dec 20 '18 at 20:01

1 Answers1

1

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)
Mark
  • 90,562
  • 7
  • 108
  • 148