首页 > 关于jQuery序列化表单项

关于jQuery序列化表单项

主要是卡在establish下面这一块了,很少写JS,所以没啥经验,序列化之后是的表单是这样子的:

firm=ABC
location=USA
establish=1979
name=A
position=Designer
tel=12345678
email=example1@example.com
name=Mizuki
position=Programmer
tel=56473829
email=example2@example.com
name=FullStack
position=Engineer
tel=17012345
email=example3@example.com

怎么把上面这一块处理JSON,如下:

"firm" : "ABC",
"location" : "USA",
"establish" : "1979",
"contacts" : [
    {
        "name" : "A",
        "position" : "Designer",
        "tel" : "12345678",
        "email" : "example1@example.com"
    },
    ...
    ...
]

求点拨~


// 将表单序列化为JSON对象
$.fn.json = function () {
    return JSON.parse( '{' + this.serializeArray().map( function ( x ) { return '"{0}":"{1}"'.replace( '{0}', x.name ).replace( '{1}', x.value ) }).join() + '}' );
};

// 使用方法
$('form').json();

为了方便,用的 ES2015 的语法

let text = `
firm=ABC
location=USA
establish=1979
name=A
position=Designer
tel=12345678
email=example1@example.com
name=Mizuki
position=Programmer
tel=56473829
email=example2@example.com
name=FullStack
position=Engineer
tel=17012345
email=example3@example.com
`;

let contacts = {
    _start: "name",
    name: true,
    position: true,
    tel: true,
    email: true
};

let contact;

let result = text.trim()
    .split(/[\r\n]+/)
    .reduce((r, line) => {
        let m = line.match(/^(.+?)=(.+$)/);
        if (!m) {
            return r;
        }

        let key = m[1];
        let value = m[2];
        if (key === contacts._start) {
            contact = {};
            (r.contacts = r.contacts || []).push(contact);
        }

        if (contacts[key]) {
            contact[key] = value;
        } else {
            r[key] = value;
        }

        return r;
    }, {});

let json = JSON.stringify(result, null, 4);

JSON 结果

{
    "firm": "ABC",
    "location": "USA",
    "establish": "1979",
    "contacts": [
        {
            "name": "A",
            "position": "Designer",
            "tel": "12345678",
            "email": "example1@example.com"
        },
        {
            "name": "Mizuki",
            "position": "Programmer",
            "tel": "56473829",
            "email": "example2@example.com"
        },
        {
            "name": "FullStack",
            "position": "Engineer",
            "tel": "17012345",
            "email": "example3@example.com"
        }
    ]
}
【热门文章】
【热门文章】