0

I have an array which I have extracted from query string which looks like below:

var arr = 'field1=12345&status=New&status=Assigned&status=In Progress&field2=2&field3=abc&feild4=10'

I need to convert this array to JSON object. I am using the below code:

    const arr = 'field1=12345&status=New&status=Assigned&status=In Progress&field2=2&field3=abc&feild4=10'

function arrayToObject(query) {
    const uri = decodeURIComponent(query);
    const chunks = uri.split('&');
    const params = {}
    var chunk = {}
    for (var i=0; i < chunks.length ; i++) {
        chunk = chunks[i].split('=');
        console.log(chunk)
        params[chunk[0]] = chunk[1];
        }

    return params;
}
const querySt = arrayToObject(decodedQueryString);
const qSt = JSON.stringify(querySt);

console.log(qSt)

I am getting the below output: {"feild1":"12345","status":"In Progress","feild2":"2","feild3":"abc","feild4":"10"}

But I need an output like this: {"feild1":"12345","status"::["New", "Assigned", "In Progress"],"feild2":"2","feild3":"abc","feild4":"10"}

Can anyone help with this.

2 Answers 2

1

Convert the string to a URLSearchParams object. Get the keys from the object, and pass them through a Set to get the unique key. Now reduce the array of keys to an object, and use URLSearchParams.get() for single value keys, and URLSearchParams.getAll() for multiple values keys (like status):

const str = 'field1=12345&status=New&status=Assigned&status=In Progress&field2=2&field3=abc&feild4=10'

const params = new URLSearchParams(str)

const result = [...new Set([...params.keys()])]
  .reduce((acc, key) => {
    acc[key] = key === 'status' 
      ? params.getAll(key)
      : params.get(key)  
    
    return acc
  }, {})

console.log(JSON.stringify(result))

Sign up to request clarification or add additional context in comments.

Comments

0

This will work:

const arr = 'field1=12345&status=New&status=Assigned&status=In Progress&field2=2&field3=abc&feild4=10'

function arrayToObject(query) {
    const uri = decodeURIComponent(query);
    const chunks = uri.split('&');
    const params = {}
    var chunk = {}
    for (var i=0; i < chunks.length ; i++) {
        chunk = chunks[i].split('=');
        console.log(chunk)
        if (params[chunk[0]]){
        params[chunk[0]] = Array.isArray(params[chunk[0]]) ? [...params[chunk[0]], chunk[1]] : [params[chunk[0]], chunk[1]];
        } else {
        params[chunk[0]] = chunk[1];
        }
        }

    return params;
}
const querySt = arrayToObject(arr);
const qSt = JSON.stringify(querySt);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.