1
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

I suggest you use the standard query string syntax to avoid future problems. Because the weirder this query string gets, the more cases you'll have to add to this piece of code. And when a case that's not covered in your code appears, it will unexpectedly break your code.

Also, this used to be the way to parse query strings (i.e. split by &, loop through the items, split by =). Now, there is a built-in API, URLSearchParams, that parses query strings for you. It exists for both browser JS as well as NodeJS. It exposes several methods as well as methods that return iterables, which allow you to loop through the items.

\$\endgroup\$
  • \$\begingroup\$ Thank you for the answer but the question is not specific about URL parameters \$\endgroup\$ – Manjeet Thakur May 19 '19 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.