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">

6
  • Why not use .each()? Commented Jan 20, 2016 at 1:14
  • Also, your second class does not match. Think you want both to be aws. Commented Jan 20, 2016 at 1:14
  • Possible duplicate of Add new object to array Commented Jan 20, 2016 at 1:18
  • @Twisty that doesn't matter, it's just a typo Commented Jan 20, 2016 at 1:20
  • 2
    You are getting undefined because you are using the wrong length condition in your for loop, the bigger problem is that you are adding the same object to the array in each iteration so each object is going to be exactly the same Commented Jan 20, 2016 at 1:28

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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

6 Comments

I know I can do this but why native JS have problem?
Why did you Post to Jquery if you wanted Native solution?
This is going to have the same problem, you are adding the same object in each iteration, you are overwriting the same property of the same object.
I suspect the issue with your native code comes in with the limit: len = $('.aws').length + 1;, this would be 3. When i is incremented, 0, 1, 2, 3... it will not have an object to find. Should be 2, with a < limit. 0, 1, those are all the items.
your solution is broken, the value is repeated, 2.jpg twice.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.