Iterating every other AJAX object - javascript

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

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/

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

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

Related

Problem with Javascript localStorage for-loop

I am using localStorage to store incoming message: {"lastTid":22,"Hour":10,"min":31,"Second":34} where the time is increasing in every new incoming object, e.g. next object: {"lastTid":22,"Hour":10,"min":31,"Second":35}.
The new messages are being stored in localStorage correctly as seen here:
My Javascript code implements the localStorage.getItem and .setItem correctly to retrieve and get my incoming data message, which will be rendered with .innerHTML to var hst, which hst = document.getElementById("highscores"). all code below
The ElementId "highscores" is assigned to <table> tag in my html and comes out as seen here:
#js code snippet#
var hst = document.getElementById("highscores");
function onMessageArrived(message) {
var data = JSON.parse(message.payloadString);
var highScores = [data];
var array = JSON.parse(localStorage.getItem('highscores') || '[]');
array.push(highScores);
localStorage.setItem('highscores', JSON.stringify(array));
for (var i = 0; i < array.length; i++) {
hst.innerHTML += "<tr><td>" + array[i][0].Hour + ":"+ array[i][0].min + ":" + array[i][0].Second + "</td><td>" + array[i][0].lastTid + "</td></tr>";
}
};
My problem is, because of my For loop, when a new message arrives, my loop goes through and renders the previous message and the new message, while the old message is still in the table(please see the table image above). It is displaying object 0, object 0 & 1, then object 0, 1 & 2 all in the same table. Instead of 0, then 1 after, then 2 ... n.
I wish to display the values in proper order and also keep those values even after the page is reloaded. Desired result:
Don't append directly hst.innerHTML +=...
try something like this
let html = ''
for (var i = 0; i < array.length; i++) {
html += "<tr><td>" + array[i][0].Hour + ":"+ array[i][0].min + ":" + array[i][0].Second + "</td><td>" + array[i][0].lastTid + "</td></tr>";
}
hst.innerHTML = html
I think the problem is your always appending the array content at hst.innerHTML each incoming message, so the previous loop content remains. It's also not recommended for performance to manipulate DOM inside loops.
let res = '';
for (var i = 0, l = array.length; i < l; i++) {
res += '<tr><td>' + array[i][0].Hour + ':' + array[i][0].min + ':' + array[i][0].Second + '</td><td>' + array[i][0].lastTid + '</td></tr>';
}
hst.innerHTML = res; // You overwrite the content instead of appending each time.

Compare arrays with JS and print result in matrix table

I am trying to make a matrix table by combining values from array. First array holds information about user for specific day. Second array holds list of users, third array holds days in month.
First I get data from api.
var odgovor = JSON.parse(http.responseText);
dataSetMoj = odgovor.urvPoDanuZaMjesec;
dataSetMojUposlenik = odgovor.uposlenici;
Get days for month
var mjesecImaDana = getDaysInMonth(1,2018);
var daniMjeseca = [];
for (i = 1; i <= mjesecImaDana; i++) {
daniMjeseca.push([i]);
}
Then I create table header
var k = '<thead>';
k +='<tr><th style="background-color: #f8f7f7" >' + rb + '</th>';
k +='<th style="background-color: #f8f7f7" >' + up + '</th>';
daniMjeseca.forEach(function(daysInmonth){
k += '<th style="background-color: #f8f7f7"> '+ daysInmonth +'</th>';
});
k += '</tr></thead>';
Table header display correct information, as could be seen in img.
Array rezultati holds information about each user on specific day
var rezultati = [];
for(i = 0;i < dataSetMoj.length; i++){
rezultati.push(dataSetMoj[i].ime+'-'+dataSetMoj[i].datum+'-'+dataSetMoj[i].urv);
}
Then I create table body, In table body I should match user with date.
k += '<tbody>'
for(i = 0;i < dataSetMojUposlenik.length; i++){
k+='<tr>';
k+='<td> ' + a++ + '</td>';
k+='<td> ' + dataSetMojUposlenik[i].ime + '</td>';
daniMjeseca.forEach(function(daysInmonth){
var dataSetVar = dataSetMojUposlenik[i].ime +'-'+daysInmonth;
//here I should check if variable 'datSetVar' is set in array rezultati, if yes I should print dataSetMoj[i].urv from rezultati
if(rezultati == dataSetVar ){
k+='<td> ' + dataSetMoj[i].urv + '</td>'; // It does not work, but I have no idea. I could not find solution any hint would help me.
}
else{
k+='<td> ' + c + '</td>';
}
});
k+='</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
Array rezultati holds three element dataSetVar two. I am not able to make comparison got wrong answers.

First element in object is undefined using += operator

I have a problem to use the operator += in an object.
Because i have to change the variable dynamically i use an object as variable.
But if i use the += operator the first element in the output always gets undefined. I think thats because the object is initialized empty.
What is the best solution to prevent to output that element ?
Here goes my example code:
var dynamicVariable = {};
var group = "apples";
for(var i = 1; i<5; i++)
{
dynamicVariable[group] += " Apple" + i + "<br>";
}
document.getElementById("fruits").innerHTML = dynamicVariable[group];
jsFiddle
This is happening because dynamicVariable[group] has the value undefined before you start appending to it. undefined + " Apple1" is "undefined Apple1".
You need to initialize it to an empty string first:
dynamicVariable[group] = "";
for(var i = 1; i<5; i++) {
dynamicVariable[group] += " Apple" + i + "<br>";
}

Javascript - split string and output results on separate lines

What I'm trying to do is take a comma separated string like "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress" - split that string into and array and write a loop that outputs each array item on a separate line.
This works:
function splitstr() {
var splitStr = "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress";
var output = splitStr.split(',');
for (var i = 0; i < output.length; i++) {
document.write(output[i] + "<br />");
}
}
but obviously it outputs to a blank page. I need it to output the results into a div.
So I try the following code but it doesn't work. It only prints out the last one "Wordpress".
function splitstr() {
var splitStr = "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress";
var output = splitStr.split(",");
for (var i = 0; i < output.length; i++) {
document.getElementById("splitres").innerHTML = output[i] + "<br />";
}
}
what am i doing wrong?
agon
document.getElementById("splitres").innerHTML += output[i] + "<br />";
Note +. With that, you are appending HTML; without it, you are overwriting it.

FOR IF Loop in javascript

I have a simple question. I want to make an if statement in this code (if(i=2){str += 'test';}):
var data = response.DATA;
var str = '<ul>';
for (var I = 0; I < data.length; I++) {
str += '<li>' + data[I][1] + '</li>';
if(I=2){str += 'test';}
}
str += '</ul>';
$('#output').html(str);
}
When I do, it's placing the word 'test' not only at row 2, but on every row.
Use == or === to compare two values :
if (I===2) {str += 'test';}
The result of I=2, which changes the value of I, is 2, which evaluates as true in an if.
You have a typo in your script:
if (I=2) ...
means that I is always 2 because you're assigning 2 to it.

Categories

Resources