Created
September 7, 2017 22:17
-
-
Save ztane/8c97ae26aa35dfaec5a8103d61459742 to your computer and use it in GitHub Desktop.
jsonSerialize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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