1

I want to loop through a list of element which have dynamic name's value, like item1,item2 etc. but I got undefined like below.

len = $('.aws').length + 1;

var obj = [],
  temp = {};

for (var i = 1; i <= len; i++) {
  console.log(i)
  temp["index"] = $('.aws[name="item' + i + '"]').val()
  obj.push(temp);
}

console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="aws" name="item1" value="1.jpg">
<input type="hidden" class="aws" name="item2" value="2.jpg">
Nichole A. Miler
  • 1,281
  • 2
  • 11
  • 21

2 Answers2

1

The problem is that you're pushing a reference to the same object on each iteration. In doing so, the index property on the temp object will be the value from the last iteration.

In addition, there are only two elements, and the for loop was executed three times because of the condition i <= len (it should have been i < len). Due to this, the value was undefined on the last iteration, because the element doesn't exist. This resulted in all the index properties on the temp property being set to undefined.

If you want a native JS solution, you could simply use the following instead:

var elements = document.querySelectorAll('.aws');
var values = [];

for (var i = 0; i < elements.length; i++) {
  values.push({index: elements[i].value});
}

In the snippet above, a new object is pushed to the values array on each iteration (rather than a reference to the same object). The for loop condition is also i < elements.length (rather than i <= elements.length), so it will only iterate 2 times (rather than 3 like in your example).


If you want a shorter jQuery solution, simply use the .map() method:

var values = $('.aws').map(function () {
  return {index: this.value };
}).get();
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
0

Try this: https://jsfiddle.net/Twisty/ys889cn6/1/

var obj = [],
  temp = {};

$(document).ready(function() {
  $(".aws").each(function(i, v) {
    obj.push({ "index": $(this).val() });
  });
  console.log(obj);
});

Much easier to loop this way. Read more: https://api.jquery.com/each/

Somewhat Native

$(document).ready(function() {
  var obj = [],
    temp = {},
  len = $('.aws').length;
  for (var i = 0; i < len; i++) {
  console.log("Get Value from: .aws[name='item" + (i+1) + "']");
    temp["index"] = $(".aws[name='item" + (i+1) + "']").val();
    obj.push(temp);
  }
  console.log(obj);
});

As @PatrickEvans stated, we're just dropping the same object in. Results:

Get Value from: .aws[name='item1']
Get Value from: .aws[name='item2']
[Object { index="2.jpg"}, Object { index="2.jpg"}]

Fixed by using:

$(document).ready(function() {
  var obj = [],
    temp = {},
  len = $('.aws').length;
  for (var i = 0; i < len; i++) {
  console.log("Get Value from: .aws[name='item" + (i+1) + "']");
    obj.push({"index": $(".aws[name='item" + (i+1) + "']").val()});
  }
  console.log(obj);
});
Twisty
  • 30,304
  • 2
  • 26
  • 45