Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse input[] values and put them into a Javascript Array

Tags:

javascript

Let's say i have this:

<form id='foo'>
 <input name='bar[name]' />
 <input name='bar[age]' />
</form>

How can i get the values of array inputs within the form foo and put them into an associative array/object like this:

var result = {bar:{name:'blah',age:21}};

P.S. I don't want to use any frameworks for this.

like image 501
CodeOverload Avatar asked Aug 26 '11 21:08

CodeOverload


3 Answers

I needed to do this myself and after finding this question I didn't like any of the answers: I don't like regex and the others are limited.

You can get the data variable many ways. I'll be using jQuery's serializeArray method when I implement this.

function parseInputs(data) {
    var ret = {};
retloop:
    for (var input in data) {
        var val = data[input];

        var parts = input.split('[');       
        var last = ret;

        for (var i in parts) {
            var part = parts[i];
            if (part.substr(-1) == ']') {
                part = part.substr(0, part.length - 1);
            }

            if (i == parts.length - 1) {
                last[part] = val;
                continue retloop;
            } else if (!last.hasOwnProperty(part)) {
                last[part] = {};
            }
            last = last[part];
        }
    }
    return ret;
}
var data = {
    "nom": "123",
    "items[install][item_id_4]": "4",
    "items[install][item_id_5]": "16",
    "items[options][takeover]": "yes"
};
var out = parseInputs(data);
console.log('\n***Moment of truth:\n');
console.log(out);
like image 122
smdvlpr Avatar answered Nov 16 '22 15:11

smdvlpr


You can map the elements to an object like this.

function putIntoAssociativeArray() {

    var 
        form = document.getElementById("foo"),
        inputs = form.getElementsByTagName("input"),
        input,
        result = {};

    for (var idx = 0; idx < inputs.length; ++idx) {
        input = inputs[idx];
        if (input.type == "text") {
            result[input.name] = input.value;
        }
    }

    return result;
}
like image 33
Wyatt Avatar answered Nov 16 '22 15:11

Wyatt


var form = document.getElementById( 'foo' );
var inputs = form.getElementsByTagName( "input" );
var regex = /(.+?)\[(.+?)\]/;
var result = {};
for( var i = 0; i < inputs.length; ++i ) {
    var res = regex.exec( inputs[i].name );
    if( res !== null ) {
        if( typeof result[ res[1] ] == 'undefined' ) result[ res[1] ] = {};
        result[ res[1] ][ res[2] ] = inputs[i].value;
    }
}
like image 2
nobody Avatar answered Nov 16 '22 15:11

nobody