[英]How to convert array of srting with multiple same keys to JSON Object?
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' var arr = 'field1=12345&status=新建&status=已分配&status=进行中&field2=2&field3=abc&feild4=10'
I need to convert this array to JSON object.我需要将此数组转换为 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"}我得到以下 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"}但我需要一个 output 像这样: {"feild1":"12345","status"::["New", "Assigned", "In Progress"],"feild2":"2","feild3":" abc","feild4":"10"}
Can anyone help with this.有人能帮忙吗。
Convert the string to a URLSearchParams object.将字符串转换为URLSearchParams object。 Get the keys from the object, and pass them through a Set to get the unique key.
从 object 中获取密钥,并通过Set传递它们以获取唯一密钥。 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
):现在将键数组缩减为 object,并将 URLSearchParams.get
URLSearchParams.get()
用于单值键,将 URLSearchParams.getAll 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))
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.