I have values of form as follow
<input name="Document[0][category]" value="12" type="text">
<input name="Document[0][filename]" value="abca.png" type="text" >
I want to serialize it to an object by js or jquery.
Document[0]={
category : 12
filename : 'abca.png'
};
I try use serializeArray
and parse to object but no good
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.
To replace a DOM element in the DOM tree, you follow these steps: First, select the DOM element that you want to replace. Then, create a new element. Finally, select the parent element of the target element and replace the target element by the new element using the replaceChild() method.
Low-tech method:
var Document = [];
var inputs = document.querySelectorAll('input');
Array.prototype.forEach.call(inputs, function(input) {
var name = input.getAttribute('name');
var prevProp = null;
var obj = Document;
name.replace(/\[(.*?)\]/g, function(m, prop) {
if (prevProp) obj = obj[prevProp] || (obj[prevProp] = {});
prevProp = prop;
});
obj[prevProp] = input.value;
});
console.log(Document);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="Document[0][category]" value="12" >
<input name="Document[0][filename]" value="abca.png" >
</form>
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
EDIT: as guest271314 notes, using Document
as a variable name might not be the greatest idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With