#需求背景
1.如果表单 <input />
的 name
等于数组类型的时候 例如
<input type="checkbox" name="plugins[0][multi_merchant]" title="多商户" checked>
<input type="checkbox" name="plugins[1][multi_merchant]" title="多商户" checked>
<input type="checkbox" name="plugins[2][multi_merchant]" title="多商户" checked>
...
2.原先 JQ.serializeArray(formObject)
序列化后会变成这样
{
0: {name: "plugins[1][sass]", value: "on"}
1: {name: "plugins[1][multi_merchant]", value: "on"}
2: {name: "plugins[1][store]", value: "on"}
3: {name: "plugins[1][share_sale]", value: "on"}
4: {name: "plugins[1][wholesale]", value: "on"}
5: {name: "plugins[1][cashback]", value: "on"}
6: {name: "plugins[1][nine_luck_draw]", value: "on"}
7: {name: "plugins[1][os_min_alipay]", value: "on"}
8: {name: "plugins[1][os_min_wechat]", value: "on"}
9: {name: "plugins[1][os_android]", value: "on"}
10: {name: "plugins[1][os_ios]", value: "on"}
11: {name: "plugins[1][os_h5]", value: "on"}
12: {name: "customer_id", value: "5"}
}
- 那么如何才能让他变成一个这样的数组呢
{
plugins: {
1: {
sass: "on",
multi_merchant: "on",
...
}
}
}
- 请看下列代码
function formToArray(arr) {
let obj = {};
for(let i in arr) {
let key = arr[i].name;
let val = arr[i].value;
let index = key.indexOf("[");
if(index > -1) {
// 获取 Keys
let keys = [];
keys.push(key.substr(0, index)); // 第一个
let reg = /\[(.+?)\]/g;
let iarr = key.match(reg);
for(let ia in iarr) {
keys.push(iarr[ia].substr(1, iarr[ia].length - 2));
}
let keyCount = keys.length;
// 循环写入值
let cur = undefined;
for(let ik in keys) {
let k = keys[ik];
if(cur === undefined) {
if(obj[k] === undefined) {
obj[k] = {};
}
cur = obj[k];
} else {
if(cur[k] === undefined) {
cur[k] = {};
}
if(ik > (keyCount - 2)) {
cur[k] = val;
} else {
cur = cur[k];
}
}
}
cur = val;
} else {
obj[key] = val;
}
}
return obj;
}