user11929397
user11929397

Reputation:

Iterate over json data with jquery

When I alert the output in the example below I get the correct output, but when I console.log the output, I get: Number {}

"width": [ 25, 50, 75, 100 ],

jQuery.each(width, function() {
  new_width = this;
  console.log(new_width);
  alert(new_width);
  document.querySelectorAll('#source').forEach(function (element, index) {
    element.style.width = new_width;
  });
});

Upvotes: 1

Views: 29

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337700

The issue is because you're using jQuery.each() to loop through the array. When accessing via this you receive a Number object, not an integer value, hence the {} output to the log. There's several ways to fix this:

1) Use the arguments passed to the function instead of the this reference:

var foo = { "width": [ 25, 50, 75, 100 ] }
jQuery.each(foo.width, function(i, value) {
  console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2) Use toString() or valueOf() on the object. Side note, alert() in your question works because it calls toString() under the hood.

var foo = { "width": [ 25, 50, 75, 100 ] }
jQuery.each(foo.width, function() {
  console.log(this.toString());
  console.log(this.valueOf());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

3) Don't use jQuery to loop through a plain array of values. Use a forEach() loop:

var foo = { "width": [ 25, 50, 75, 100 ] }
foo.width.forEach(function(value) {
  console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

My preference is for the latter method, but any of them work.

Upvotes: 1

Related Questions