简体   繁体   English

如何从多个HTML输入创建key:value对象

[英]How to create a key:value object from several HTML inputs

I got the following HTML: 我得到以下HTML:

<div class="slot_subclass">
   <div class="form-group">      
        <input type="text" class="form-control slot" name="slot_name">      
   </div>
   <div class="form-group"> 
        <input type="text" class="form-control slot" name="slot_type">
   </div> 
</div> 
<div class="slot_subclass">
   <div class="form-group">      
        <input type="text" class="form-control slot" name="slot_name">      
   </div>
   <div class="form-group"> 
        <input type="text" class="form-control slot" name="slot_type">
   </div> 
</div>
<div class="slot_subclass">
   <div class="form-group">      
        <input type="text" class="form-control slot" name="slot_name">      
   </div>
   <div class="form-group"> 
        <input type="text" class="form-control slot" name="slot_type">
   </div> 
</div>  

The amount of slot_subclass may be unlimited. slot_subclass的数量可以是无限的。

I need to parse all these inputs and make an object where the key is the value of first input of slot_subclass ( slot_name ) and value is the value of the second ( slot_type ). 我需要解析所有这些输入,并创建一个对象,其中键是slot_subclassslot_name )的第一个input的值,value是第二个( slot_type )的值。

I tried the following: 我尝试了以下方法:

$(".slot").map(function(){
    return $(this).val();
}).get();

but I just get a plain array of values. 但是我只是得到一个简单的值数组。 I may use jQuery for this task. 我可以将jQuery用于此任务。 Thank you. 谢谢。

UPD_1 In order to handle for the same keys I chose the following code (if someone interested): UPD_1为了处理相同的键,我选择了以下代码(如果有兴趣的话):

jsonObj = [];
$(".slot_subclass").each(function() { 
    var slot_name = $(this).find("input[name=slot_name]").val();
    var slot_type = $(this).find("input[name=slot_type]").val();
    item = {};
    item[slot_name] =  slot_type;
    jsonObj.push(item);
});
console.log(jsonObj);

Thank you everyone for help. 谢谢大家的帮助。

Like this code: 像这样的代码:

100% working and tested 100%工作和测试

jsonObj = [];
$(".slot_subclass").each(function() { 
    var slot_name = $(this).("input[name=slot_name]").val();
    var slot_type = $(this).("input[name=slot_type]").val();
    item = {};
    item["slot_name"] = slot_name;
    item["slot_type"] = slot_type;
    jsonObj.push(item);
});
console.log(jsonObj);

Example: 例:

 jsonObj = []; $(".slot_subclass").each(function() { var slot_name = $(this).find("input[name=slot_name]").val(); var slot_type = $(this).find("input[name=slot_type]").val(); item = {}; item["slot_name"] = slot_name; item["slot_type"] = slot_type; jsonObj.push(item); }); console.log(jsonObj); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name" value="1"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type" value="11"> </div> </div> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name" value="2"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type" value="22"> </div> </div> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name" value="3"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type" value="33"> </div> </div> 

Firstly note that there's no such thing as a 'JSON object'. 首先请注意,没有“ JSON对象”之类的东西。 JSON is a notation for serialising data to a string. JSON是用于将数据序列化为字符串的符号。 It's never an object. 它从来不是一个对象。

With regard to your code, map() returns an array. 关于您的代码, map()返回一个数组。 In your example this array will contain values only. 在您的示例中,此数组将仅包含值。 Instead you need to change that to return an object that holds the values of the input elements within each .slot_subclass group. 相反,您需要更改它以返回一个对象,该对象包含每个.slot_subclass组中的input元素的值。

Once you've done that to build the array, you can use JSON.stringify to build your JSON string, something like this: 一旦完成构建数组,就可以使用JSON.stringify构建JSON字符串,如下所示:

 var arr = $('.slot_subclass').map(function() { var obj = {}; $(this).find('.slot').each(function() { obj[this.name] = this.value; }); return obj; }).get(); console.log(arr); var json = JSON.stringify(arr); console.log(json); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> 

Following is based on : 以下基于:

where key is the value of first input 其中key是第一个输入的值

 // set values for demo setDemoValues() // get data based on above values var res = {}; $('.slot_subclass').each(function() { var $inputs = $(this).find('.slot'); res[$inputs[0].value] = $inputs[1].value; }) console.log(res) function setDemoValues() { $('.slot_subclass').each(function(i) { $(this).find('.slot').val(function() { return this.name + (i + 1); }) }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> 

So, what you can do is query all of the inputs, set their name as the key and their value as their input. 因此,您可以做的是查询所有输入,将其名称设置为键,并将其值设置为输入。

The problem you can run into, if you just do it as you have it now, is that your values will be overridden since you have multiple inputs with the same name. 如果您现在就这样做,可能会遇到的问题是,由于您有多个具有相同名称的输入,因此您的值将被覆盖。

You can get around that by adding a unique ID or class to their parent container. 您可以通过向其父容器添加唯一的ID或类来解决此问题。

var inputs = document.querySelectorAll("input");
var data = {};
for (var i = 0; i < inputs.length; i++) {
    data[inputs[i].name] = inputs[i].value;
}

console.log(data);

For getting a specific set of inputs, using the unique identifier I mentioned above, all you have to do is change the query selector. 为了获得一组特定的输入,使用上面提到的唯一标识符,您要做的就是更改查询选择器。

var inputs = document.querySelectorAll("#container input");

EDIT 编辑

Having an unknown amount of subclasses you can put them into an array. 您可以将未知数量的子类放入一个数组中。 Following the same JS above, it's just one extra step. 遵循上述相同的JS,这只是一个额外的步骤。

var subclasses = document.querySelectorAll(".slot_subclass");
var data = [];
for (var i = 0; i < subclasses.length; i++) {
    if (!data[i]) data[i] = {};
    var inputs = subclasses[i].querySelectorAll("input");
    for (var o = 0; o < inputs.length; o++) {
        data[i][inputs[o].name] = inputs[o].value;
    }
}

console.log(data);
// outputs like: 
[
    0: {slot_name: "", slot_type: ""}
    1: {slot_name: "", slot_type: ""}
    2: {slot_name: "", slot_type: ""}
]

You're on a right way but you need to change you algorithm. 您的方法正确,但需要更改算法。 Let's see $(".slot_subclass") is array of div elements - iterate that array, and got both 'key' and 'value' values :). 让我们看一下$(".slot_subclass")是div元素的数组-迭代该数组,并同时获得'key'和'value'值:)。 For each element of $(".slot_subclass") you can get access to first and second nested inputs by something like $(el).find('.slot') and first element of that array is a first input, second is a second input. 对于$(".slot_subclass")每个元素,您都可以通过$(el).find('.slot')类的东西来访问第一和第二嵌套输入,并且该数组的第一个元素是第一个输入,第二个是一个第二个输入。

You should use each() , not map() 您应该使用each() ,而不是map()

 $('.test').on('click', function() { var obj = {} $(".slot_subclass").each(function() { var $slots = $(this).find('.slot'); obj[$slots.eq(0).val()] = $slots.eq(1).val() }) console.log(obj) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> <div class="slot_subclass"> <div class="form-group"> <input type="text" class="form-control slot" name="slot_name"> </div> <div class="form-group"> <input type="text" class="form-control slot" name="slot_type"> </div> </div> <button class="test">Test</button> 

Use this : 用这个 :

var res = {};
var names = $('.slot[name="slot_name"]');
var types = $('.slot[name="slot_type"]');
for (var i=0;i<names.length;i++) {
    res[$(names[i]).val()]=$(types[i]).val();
}
console.log(res); // = {"name1":type1,...,"nameN":typeN}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM