Skip to content

Instantly share code, notes, and snippets.

@ztane
Created September 7, 2017 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ztane/8c97ae26aa35dfaec5a8103d61459742 to your computer and use it in GitHub Desktop.
Save ztane/8c97ae26aa35dfaec5a8103d61459742 to your computer and use it in GitHub Desktop.
jsonSerialize
(function ($) {
function doSerializeArrayItems($current, target) {
$current.children().each(function (i, e) {
var $e = $(e),
tmp;
if (e.hasAttribute('data-form-item')) {
var o = {};
target.push(o);
doSerialize($e, o);
}
else if (tmp = $e.prop('name')) {
console.log('Warning, ignoring named element in an array ' + tmp);
console.log(e);
}
});
}
function doSerialize($current, obj) {
var tmp, value;
if ($current.attr('name')) {
var newItems = $current.serializeArray();
if (newItems.length) {
$.each(newItems, function (i, e) {
var name = e.name,
value = e.value;
if (name.substring(name.length - 2) === '[]') {
name = name.substring(0, name.length - 2);
if (!obj[name]) {
obj[name] = [];
}
obj[name].push(value);
}
else {
obj[name] = value;
}
});
}
}
else if (tmp = $current.data('formArray')) {
var l = obj[tmp] = [];
doSerializeArrayItems($current, l);
}
else {
$current.children().each(function (i, e) {
doSerialize($(e), obj);
});
}
};
$.fn.jsonSerialize = function jsonSerialize() {
var obj = {};
if (! this.length) {
return undefined;
}
doSerialize($(this[0]), obj);
return obj;
};
} ($));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment