forked from macek/jquery-serialize-object
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.serialize-object.js
47 lines (47 loc) · 1.41 KB
/
jquery.serialize-object.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
(function($) {
return $.fn.serializeObject = function() {
var json, patterns, push_counters,
_this = this;
json = {};
push_counters = {};
patterns = {
validate: /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
key: /[a-zA-Z0-9_]+|(?=\[\])/g,
push: /^$/,
fixed: /^\d+$/,
named: /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value) {
base[key] = value;
return base;
};
this.push_counter = function(key) {
if (push_counters[key] === void 0) {
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function(i, elem) {
var k, keys, merge, re, reverse_key;
if (!patterns.validate.test(elem.name)) {
return;
}
keys = elem.name.match(patterns.key);
merge = elem.value;
reverse_key = elem.name;
while ((k = keys.pop()) !== void 0) {
if (patterns.push.test(k)) {
re = new RegExp("\\[" + k + "\\]$");
reverse_key = reverse_key.replace(re, '');
merge = _this.build([], _this.push_counter(reverse_key), merge);
} else if (patterns.fixed.test(k)) {
merge = _this.build([], k, merge);
} else if (patterns.named.test(k)) {
merge = _this.build({}, k, merge);
}
}
return json = $.extend(true, json, merge);
});
return json;
};
})(jQuery);