Reputation: 85
I have a JSON encoded AJAX object array and I need to iterate every other one. I'm new to jQuery and JS and are unsure how to do this. I need the numbers to be the option value and the string name as the object name.
The AJAX object (note although in this example the numerals are in order they might not be because the integers are an auto_id from a database and numbers might be skipped or out of order:
{"data":["1","chicken","2","beef","3","fish","4","pork","5","turkey","6","lamb","7","vennison","8","duck"],"error":false}
I tried the following code below which doesn't work. I tried to do a search for this answer but couldn't find it. TIA. Currently, newOption is returning "undefined".
$.each(data.data, function(i,s){
var count=s[i];
var newOption = s[i+1];
output += '<option value="' + count + '">' + newOption + '</option>';
i++;
});
Upvotes: 1
Views: 53
Reputation: 6698
Can you use an if
statement with modulus? And then initialize your count
outside the loop.
var count = 0;
$.each(data.data, function(i,element){
if (i % 2 == 0) {
count++;
output += '<option value="' + count + '">' + element + '</option>';
}
i++;
});
Upvotes: 1
Reputation: 1491
When Iterating over a Array using jQuery.each the first param is index and the second one is value in the index itself.
Instead of using jQuery use plain javascript.
try the following:
var d = data.data;
var output = "";
for (var i = 0 ; i< d.length; i=i+2) {
var count = d[i];
var newOption = d[i+1];
output += "<option value='"+count+"'>"+newOption+"</option>";
}
Upvotes: 1
Reputation: 27022
Use a for
loop, but increment the counter by 2 each loop:
var data = {"data":["1","chicken","2","beef","3","fish","4","pork","5","turkey","6","lamb","7","vennison","8","duck"],"error":false}
var output = '';
for(i = 0; i < data.data.length; i+=2) {
output += '<option value="' + data.data[i] + '">' + data.data[i+1] + '</option>';
}
https://jsfiddle.net/go98npym/
Upvotes: 2