thelolcat
thelolcat

Reputation: 11545

Array input field names to object

How can I break input values from fields named like this:

<input name="options[abc][def]">

into something like

{'options' : { 'abc' : { 'def' : value_of_input } } }

I tried

$('form').serializeArray()

but I get a two dimensional object with keys name liked

options[abc][def]

:|

Upvotes: 0

Views: 79

Answers (2)

softvar
softvar

Reputation: 18435

Why not just this:

HTML:

<div id="test"></div>

Script:

var opt = {'options' : { 'abc' : { 'def' : "value" } } };
document.getElementById("test").innerHTML = '<input type="text" name="' + opt + '" placeholder="'+ opt + '"/>';

JSFIDDLE

Upvotes: 1

Jan
Jan

Reputation: 1414

I found this library, which does exactly that: formToObject.js

<form id="testForm">
    <input name="options[abc][def]" value="test">
    <input type="button" value="Convert to object &raquo;" id="convertBtn">
</form>

<script src="formToObject.js"></script>
<script>
    document.getElementById('convertBtn').addEventListener('click', function() {
        console.log(new formToObject('testForm'));
        // Output: {"options":{"abc":{"def":"test"}}}
    });
</script>

Upvotes: 1

Related Questions