Skip to main content
3 of 3
edited title
200_success
  • 144.2k
  • 22
  • 188
  • 473

Convert query string into object in JavaScript

Suppose I have this query and want to convert into an object

a1.b2.article1=0&a2.article2=1&c3!article3=0&article16-abc=2

output for this should be

article1: 'DRAFT',
article2: 'REVISION',
article3: 'DRAFT',
article16: 'READY'

Please review my code. Is this the right way to do perform this task?

let a = "a1.b2.article1=0&a2.article2=1&c3!article3=0&article16-abc=2";
let con = {'0':'DRAFT', '1':'REVISION', '2':'READY'}
let obj = {};
a = a.replace(/-abc/g, "");
a = a.replace(/[.!]/g, "&");
a = a.split("&").forEach((v, i) => {
    let b = v.split("=");
    if (b.length > 1) {
       Object.assign(obj,{[b[0]]:con[b[1]]})
    }
});

I'm wondering if there any optimized way to do this.