如何将具有多个相同键的字符串数组转换为 JSON 对象?

How to convert array of srting with multiple same keys to JSON Object?

我有一个从查询字符串中提取的数组,如下所示:

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

我需要将此数组转换为 JSON 对象。我正在使用以下代码:

    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)

我得到以下输出: {"feild1":"12345","status":"进行中","feild2":"2","feild3":"abc","feild4":"10"}

但我需要这样的输出: {"feild1":"12345","status"::["新建", "已分配", "进行中"],"feild2":"2","feild3":"abc","feild4":" 10"}

谁能帮忙解决一下。

这会起作用:

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);

将字符串转换为 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() 用于多个值键(如 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))