我有一个字符串:
"id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1"
现在,我想获得一个对象数组,通过像这样的ajax传递给控制器:
[{"id":1, "lotcode"="ACB","location":"A1"},{"id":2, "lotcode"="CCC","location":"B1"}]
我首先分割字符串
var string = data.split('&', 2);
现在我被困在这里...
答案 0 :(得分:3)
您可以将字符串除以&
,然后将键/值对分配给具有递增索引的数组。
此解决方案假定所有键都具有相同的计数。
var string = "id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1",
result = [],
indices = {};
string.split('&').forEach(s => {
var [key, value] = s.split('='),
index = (indices[key] || 0);
result[index] = result[index] || {};
result[index][key] = value;
indices[key] = index + 1;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }