I have a string that looks like this:
'a=aaa,bbb,ccc&b=aaa,bbb,ccc&c=aaa,bbb,ccc'
and I want to change it into an object that looks like this:
{ a: 'aaa, bbb, ccc', b: 'aaa, bbb, ccc', c: 'aaa, bbb, ccc' }
I've tried splitting on the &
and then =
but that results in:
[ ['a', 'aaa','bbb','ccc'], ['b', 'aaa','bbb','ccc'], ['c', 'aaa','bbb','ccc' ] ]
You could just use URLSearchParams:
var params = new URLSearchParams('a=aaa,bbb,ccc&b=aaa,bbb,ccc&c=aaa,bbb,ccc');
var obj = Object.fromEntries(params.entries())
console.log(obj);
If your browser doesn't have either of those functions, you can use a polyfill:
https://www.npmjs.com/package/url-search-params-polyfill https://github.com/feross/fromentries
If you want to just use split()
, you need to make the object out of the split keys and values. You can do this in a reduce
loop (or a forEach()
):
s = 'a=aaa,bbb,ccc&b=aaa,bbb,ccc&c=aaa,bbb,ccc'
let pairs = s.split('&') // each pair is like a=aaa,bbb,ccc
let obj = pairs.reduce((obj,data)=> {
let [k, v] = data.split('=') // split each pair into key/value
obj[k] = v // add the key to the object
return obj
}, {})
console.log(obj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With