Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting DOM elements into Objects

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

like image 564
dieuvn3b Avatar asked Dec 01 '15 01:12

dieuvn3b


People also ask

Are DOM elements objects?

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.

How do I change a DOM element?

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.


1 Answers

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.

like image 62
Amadan Avatar answered Sep 28 '22 22:09

Amadan