Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string into object with key value pairs

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' ] ]

like image 594
UXCODA Avatar asked Mar 04 '23 23:03

UXCODA


2 Answers

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

like image 180
dave Avatar answered Mar 16 '23 12:03

dave


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)
like image 30
Mark Avatar answered Mar 16 '23 14:03

Mark