JavaScript loop through JSON data and print in html - javascript

I'm new to JavaScript and I'm trying to figure out how-to loop through JSON and print each selected value in HTML. My solution below does everything I want except print "all" rows of the JSON data. It only prints the last one. I've been researching on StackOverflow and elsewhere, but I'm not finding the solution. Sorry if this is a redundant question and thank you for your help!
//Fetch JSON from URL
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://s.codetasty.com/toddbenrud/sandBoxToddBenrud/example/songData.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var songData = (JSON.stringify(myJson));
//https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
var index;
var obj = JSON.parse(songData);
for (index = 0; index < obj.length; ++index) {
var student_name = obj[index]['name'];
var student_email = obj[index]['email'];
var song_name = obj[index]['song'];
var song_url = obj[index]['url'];
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
}
});

Inside your for loop you are reassigning your elements' content in every Iteration. It means that you fill your elements with the First item of the Array on the First time you run the for, but the Second time you run It, you replace the elements' content with the Second item of the Array. So you get only the Last Item Data.
To solve this problema, you should "increment" your element's content on each Iteration, instead of replace it. To achieve that, you replace the Lines like
document.getElementById("studentName").innerHTML = '<br>'+student_name;
With
document.getElementById("studentName").innerHTML += '<br>'+student_name;
The += operator does a concatenation on strings

Becasue you set string for elements, don't add string.
Replace from:
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
To:
document.getElementById("studentName").innerHTML += '<br>'+student_name;
document.getElementById("studentEmail").innerHTML += '<br>'+student_email;
document.getElementById("songTitle").innerHTML += '<br>'+song_name;
document.getElementById("songURL").innerHTML += '<br>'+song_url;

Related

How to return a line from an array by searching for a specific value in said line

good evening, I am trying to use a single value to search an array, and return the full line the said value is in.
The Array is set up like this in string form:
Xanax,Brand,Anxiety,Code
However, now I'm stuck with calling back only the Medication, and not the full line the Medication is in, sadly. I would like to be able to grab each variable in a line, and make them their own independent variables outside of the array so I can use them for something else.
this.importDataObject("MEDDIAGNOSISICD-10.txt", "C:/Users/dell/Documents/tab
excel/MEDDIAGNOSISICD-10.txt");
var oFile = this.getDataObjectContents("MEDDIAGNOSISICD-10.txt");
var cFile = util.stringFromStream(oFile, "utf-8");
var fileArray = cFile.split('\t');
var Med = this.getField("Medications 1");
var Index = fileArray.indexOf(Med.value);
var Call = fileArray[Index];
console.println(Call);
Any help would be wonderful!
It's because you are running the indexOf method on the whole array, you need to run it on the each value instead. Try a for loop before you check IndexOf method.
Like this:
var i, Index;
for (i = 0; i < fileArray.length; i++) {
Index = fileArray[i].indexOf(Med.value);
if(Index > -1) console.log('Your search is found in ' + fileArray[i] );
}
Note that, in here the variable Index will be 0 or larger if that search is successful. And will be of value -1 if no match is found.

Why does my for loop return only one result

The value of the search is supposed to append to the nyt api and the for loop is supposed to list all the links. I'm only getting one result for some reason but when looked through console I see that there 100s of links.
function myFunction(){
var citySearch = $("#city").val();
var NYTurl = "https://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + citySearch +
"$sort=newest&api-key=xxxxxxxxxxxxxxxxxxxxxxxx"
jQuery.getJSON(NYTurl, function (data){
var headlines = $("#headlines")
var contentUrl = data.response.docs
for(var i = 0; i < contentUrl.length; i++ ){
contentUrlLoop = contentUrl[i];
headlines.html('Link' );
}
console.log(data)
})
return false;
}
headlines.html( assigns the passed HTML string to headlines's inner HTML. So, on each iteration, you're overwriting whatever headlines had previously. Use append instead if you want to insert an <a> for every item in the response:
headlines.append('Link' );
Or, rather than making hundreds of DOM changes, you might consider coming up with a single HTML string and then appending it:
jQuery.getJSON(NYTurl, function(data) {
var headlines = $("#headlines");
var contentUrl = data.response.docs;
var htmlStr = contentUrl.reduce(
(a, { web_url }) => a + 'Link',
''
);
headlines.html('Link');
});
(perhaps enclose them in divs as well so that each link is on a new line, or make the as block, so that the HTML is readable)

How to merge duplicate values in a for loop javascript

I am new to js and I don't understand much of codes and conditions in js.
My question is simple but I need someone to give me a good example if possible as I know what I need but it is getting hard to implement that in code.
This is my code with 2 arrays where the data is coming from.
blind_tmp = '';
for (i=0; i<#All of Blind Relationship Link.length; i++){
blind_tmp = blind_tmp + '<p>[**' + #All of Element Title[i] + '**](' + #All of Blind Relationship Link[i] + ')'
};
What simple needed is that. I want merge records that are duplicates printed.
for example: if Blind Relationship link is AF44 and after 6 elements this AF44 comes again so I want both to be written like 1.AF44,2.AF44
while now it is writing the elements how they come along
example:
AF11,AF22,AF33,AF44,AF55,AF66,AF77,AF44
so in this example you see two AF44
I want them to be written like this
AF11,AF22,AF33,AF44AF44,AF55,AF66,AF77
any help with a code example is appreciated.
The idea is to iterate through each element in the blindRelationshipLink and store those elements in a temporary array which will be used to check the number of occurrence of an array element.
var blindRelationshipLink = ['AF11','AF22','AF33','AF11','AF44','AF44','AF55','AF66','AF77','AF11','AF22','AF11'];
var arrTemp = [];
var p = '';
blindRelationshipLink.forEach(function(arr){
var count = 0;
arrTemp.forEach(function(a){
if(arr === a)
count++;
});
arrTemp.push(arr);
if(count){
count++;
arr= arr + '.' + count;
}
p = p + arr + ',';
});
alert(p);
You test by running the code snippet.
This approach is not best but it may serve your purpose.
Here is a snippet
var elemArray = ['AF11', 'AF22', 'AF33', 'AF44', 'AF55', 'AF66', 'AF77', 'AF44']; // Array of elements
//A new array which which will contain elements which pass our case
var finalArray = [];
elemArray.forEach(function(item) { // loop through main array
// Check if element is present or else push the element
if (finalArray.indexOf(item) == -1) {
finalArray.push(item);
} else {
// if element is there find the index
var getIndex = finalArray.indexOf(item);
// remove the element, else there will be duplicate
finalArray.splice(getIndex, 1);
//concate the matched element
var newElem = item + item;
// push the element in specfic index
finalArray[getIndex] = newElem;
}
})
console.log(finalArray)
Current drawback with this code is what will happen if there are multiple repeated item in the main array. For example presence of AF33 more than twice.
DEMO

Javascript variable in place of string fails request to Parse.com server

I expect this will be very simple for someone. I am trying to pass some key value pairs as a query to Parse.com javascript API. The documented format is as follows and works fine:
var query = new Parse.Query("testUser");
query.containedIn("facebookID",["10101185732529914", "10101185732529915"]);
query.find()
.then(function(result){
console.log(result);
});
However I want to pull the IDs from an array and pass them in so I have used the following code to do so (the x variable being the array):
var text = '';
for (index = 0; index < x.length; index++) {
text += '"' + x[index]['$id'] + '"';
}
text += '';
var requestString = text.replace(/""/g, '", "');
If I console.log(requestString);this shows the data in the format I need, e.g. "10101185732529914", "10101185732529915"
As such the updated request code with the variable instead of the text is now:
var query = new Parse.Query("testUser");
query.containedIn("facebookID",[requestString]);
query.find()
.then(function(result){
console.log(result);
});
This however does not work, I am assuming this is due to the format of the variable. The relevant section of Parse.com API docs is here...https://parse.com/docs/js/guide#queries-query-constraints
Any help with this would be greatly appreciated.
Thanks
Ant
Sorted the problem, it wanted an array not a string, as such...
var text=[];
for (index = 0; index < x.length; index++) {
text.push(x[index]['$id']);
}
var requestString = text;
and
var query = new Parse.Query("testUser");
query.containedIn("facebookID",requestString);
query.find()
.then(function(result){
console.log(result);
});
Thanks
Ant

How do you write to a span using jQuery?

I'm trying to populate a <span></span> element on the page load with jQuery.
At the moment the value that gets populated into the span is just an integer count.
Here I have named my span userCount:
Users<span id = "userCount"></span>
I am trying to write the value of the span with no success.
$(document).ready(function () {
$.post("Dashboard/UsersGet", {}, function (dataset) {
var obj = jQuery.parseJSON(dataSet);
var table = obj.Table;
var countUsers;
for (var i = 0, len = table.length; i < len; i++) {
var array = table[i];
if (array.Active == 1) {
var name = array.Name;
}
countUsers = i;
}
userCount.innerHTML = countUsers.toString();
});
});
You don't have any usercount variable. Use $(selector) to build a jquery object on which you can call functions like html.
$('#userCount').html(countUsers);
Note also that
you don't need to convert your integer to a string manually.
if you don't break from the loop, countUsers will always be table.length-1.
you have a typo : dataSet instead of dataset. Javascript is case sensitive.
you don't need to parse the result of the request
you don't need to pass empty data : jQuery.post checks the type of the provided parameters
So, this is probably more what you need, supposing you do other things in the loop :
$.post("Dashboard/UsersGet", function (dataset) {
var table = dataset.Table;
var countUsers = table.length; // -1 ?
// for now, the following loop is useless
for (var i=0, i<table.length; i++) { // really no need to optimize away the table.length
var array = table[i];
if (array.Active == 1) { // I hope array isn't an array...
var name = array.Name; // why ? This serves to nothing
}
}
$('#userCount').html(countUsers);
});
Use .html()!
Users<span id = "userCount"></span>
Since you have assigned an id to the span, you can easily populate the span with the help of id and the function .html().
$("#userCount").html(5000);
Or in your case:
$("#userCount").html(countUsers.toString());
Change:
userCount.innerHTML = countUsers.toString();
to:
$("#userCount").html(countUsers.toString());
Instead of:
userCount.innerHTML = countUsers.toString();
use:
$('#userCount').html(countUsers.toString());
You could use
$('#userCount').text(countUsers);
to write data to span
The call back argument should be dataSet rather than dataset?

Categories