Search code examples
jqueryarraysassociative

Change two arrays into one associative array


I have this 2 following functions, to fill an array with value. I want to fill only 1 array instead of 2. How can I make an associative array ?

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>

Solution

  • Firstly JS does not have associative arrays. You can use an object instead. To create the object you simply need to loop through the required inputs, retrieve the related label and set the key/value as needed. Try this:

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