带list子表单转json

带list子表单转json

例如 :

a:123,b:123,c[0].aaa:123,c[0].bbb:234,c[1].aaa:123,c[2].bbb:234

转为:

{
	"a": 123,
	"b": 123,
	"c": [{
		"aaa": 123,
		"bbb": 234
	}, {
		"aaa": 123,
		"bbb": 234
	}]
}

function goSubmit() {
   $.ajax({
        url: 'xxxxxxxxxxxxx',
        data: JSON.stringify(serializeObject($('#form1'))),
        dataType: "json",
        contentType: "application/json",
        async: true,
        type: "post",
        success: function (data) {
          
        }
    })
}


function serializeObject(form) {
    var obj = {};
    var a = form.serializeArray();
    $.each(a, function () {
        if (this.name.indexOf("[") !== -1 && this.name.indexOf("].") !== -1) {
            let temp1 = this.name.split("[");
            let temp2 = temp1[1].split("].");
            let list_name = temp1[0];
            let list_index = parseInt(temp2[0]);
            let list_key = temp2[1];
            // console.log(list_name, '-', list_index, '-', list_key)
            if (obj[list_name]) {
                //  console.log(obj[list_name])
                let arr = obj[list_name]
                if (arr.length < list_index + 1) {
                    for (let i = arr.length; i < list_index + 1; i++) {
                        // console.log(list_index + 1)
                        let list_obj_temp = {}
                        arr.push(list_obj_temp)
                    }
                }
                let list_obj = obj[list_name][list_index];
                list_obj[list_key] = this.value || '';
            } else {
                let arr = []
                if (list_index !== 0) {
                    for (let i = 0; i < list_index + 1; i++) {
                        // console.log(list_index + 1)
                        let list_obj_temp = {}
                        arr.push(list_obj_temp)
                    }
                }
                let list_obj = {}
                list_obj[list_key] = this.value || '';
                arr.push(list_obj)
                obj[list_name] = arr;
            }
        } else {
            if (obj[this.name]) {
                if (!obj[this.name].push) {
                    obj[this.name] = [obj[this.name]];
                }
                obj[this.name].push(this.value || '');
            } else {
                obj[this.name] = this.value || '';
            }
        }
    });
    return obj;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值