Home > Blockchain >  jquery .each function using 2 selectors and adding value from selectors as key value pair to an arra
jquery .each function using 2 selectors and adding value from selectors as key value pair to an arra

Time:10-18

I am using the jquery .each function utilizing 2 selectors. When pushing the values to an array it adds them as each selector value as its own entry into the array.

in example array(100,casement,200,glider)

what I am trying to do is add them in key value pair in an array such as

array(100=>casement, 200=>glider)

What do I need to change to make this happen?

 <input name="windowNum"><input name="windowList">
 <input name="windowNum"><input name="windowList">
 <input name="windowNum"><input name="windowList">
 <input name="windowNum"><input name="windowList">

<script>
function getFields(){
  $("input[name='windowNum'], input[name='windowList']").each(function() {

      var winList = $(this).val();

      windowList.push(winList);

      //I want an array output like this from the 2 fields
      //windowList.push(input[name='windowNum'] : input[name='windowList'])
  });
}
</script>

CodePudding user response:

It is working on my end. Try to test it into this code snippet. Or I probably did not understand your expected output.

var windowList = {};

function getFields(){
  $("input[name='windowNum']").each(function() {
      var key = $(this).val();        
      windowList[key] = $(this).next().val(); 
  });
  
  console.log(windowList);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="windowNum"><input name="windowList"><br>
 <input name="windowNum"><input name="windowList"><br>
 <input name="windowNum"><input name="windowList"><br>
 <input name="windowNum"><input name="windowList">
 
 <button type="button" onclick="getFields()">Test</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use map instead of each

let arr = [100, casement, 200, glider];

arr = arr.map((v, i) = > {
    if (i % 2 === 1 || !arr[i   1]) return null;
    return `${v}=>${arr[i   1]}`;
}).filter(Boolean);

CodePudding user response:

I solved it. Here is what I did.

$("input[name='windowNum'], input[name='windowList']").each(function() {

    var winList = $(this).val();

    windowList_x.push(winList);
});

for (let i = 0; i < windowList_x.length; i =2) {

var wNum = windowList_x[i];
var wName = windowList_x[i   1];

windowList.push({number: wNum, window: wName});

}

It outputs

Array
0: Object { number: "101", window: "test a" }
1: Object { number: "102", window: "test b" }
2: Object { number: "103", window: "test c" }
3: Object { number: "104", window: "test d" }
length: 4
  • Related