将两个数组更改为一个关联数组

时间:2016-12-20 14:10:54

标签: jquery arrays associative

我有以下两个函数,用数组填充数组。我想只填充1个数组而不是2.如何创建关联数组?

var itemMetaArray = [];
var itemLabelArray = [];

$('.frm_pro_form input, .frm_pro_form select, .frm_pro_form textarea').each(function(){
    if ($(this).attr('type') != 'hidden' && ($(this).attr("type") != "submit")) {
        itemMetaArray.push($(this).attr("name"));
    }
});

$('.frm_form_field label').each(function(){
    itemLabelArray.push($(this).text());
});

console.log(itemMetaArray);
console.log(itemLabelArray);
<div id="frm_field_71_container" class="frm_form_field form-field frm_top_container"> 
  <label for="field_p0hth" class="frm_primary_label">  
    Date 
    <span class="frm_required"></span> 
  </label> 
  <input type="text" id="field_p0hth" name="item_meta[71]" value="" maxlength="10" class="frm_date" /> 
</div>

1 个答案:

答案 0 :(得分:2)

首先,JS没有关联数组。您可以改用对象。要创建对象,您只需循环访问所需的输入,检索相关的label并根据需要设置键/值。试试这个:

&#13;
&#13;
var output = {};

$('.frm_pro_form :input:not(:hidden, :submit)').each(function() {
  var key = $(this).closest('div').find('label').text().trim();
  output[key] = $(this).val();
});

console.log(output);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="frm_pro_form">
  <div id="frm_field_71_container" class="frm_form_field form-field frm_top_container">
    <label for="field_p0hth" class="frm_primary_label">
      Date #1
      <span class="frm_required"></span> 
    </label>
    <input type="text" id="field_p0hth" name="item_meta[71]" value="foo" maxlength="10" class="frm_date" />
  </div>
  <div id="frm_field_72_container" class="frm_form_field form-field frm_top_container">
    <label for="field_p0hth" class="frm_primary_label">
      Date #2
      <span class="frm_required"></span> 
    </label>
    <input type="text" id="field_p1hth" name="item_meta[72]" value="bar" maxlength="10" class="frm_date" />
  </div>
</form>
&#13;
&#13;
&#13;