如何解析 input[] 值并将它们放入 Javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7210720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:22:00  来源:igfitidea点击:

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

javascript

提问by Ryan

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 fooand put them into an associative array/object like this:

我如何获取表单中数组输入的值foo并将它们放入这样的关联数组/对象中:

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

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

PS我不想为此使用任何框架。

采纳答案by scrappedcola

This will get you the elements:

这将为您提供以下元素:

 var result = {};
    var elements = document.forms.foo.getElementsByTagName("input");
    for(var i = 0; i < elements.length; i++)
    {
       /* do whatever you need to do with each input */
    }

回答by smdvlpr

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 datavariable many ways. I'll be using jQuery's serializeArraymethod when I implement this.

您可以通过data多种方式获取变量。serializeArray当我实现这个时,我将使用 jQuery 的方法。

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);

回答by nobody

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;
    }
}

回答by Wyatt

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;
}

回答by Marc B

var inputs = document.getElementsByTagName('input');
var field_name, value, matches, result = {};
for (var i = 0; i < inputs.length; i++) {
   field_name = inputs[i].name;
   value = inputs[i].value;

   matches = field_name.match(/(.*?)\[(.*)\]/);

   if (!results[matches[0]]) {
       results[matches[0]] = {};
   }
   results[matches[0]][matches[1]] = value;
}