How to iterate through a javascript object? - javascript

I am making a server side API call. The user can input ingredients and search. When the data is submitted, I see on my terminal this as my API call:
"http://www.recipepuppy.com/api/?i=[object Object]".
I am hoping for it to look like this:
"http://www.recipepuppy.com/api/?i=milk,flour,sugar,egg"
Here is my code:
router.get("/whatCanIMake", function(request, response){
var inputIngredients = request.query;
var ingredientString = "";
console.log(inputIngredients);
for (var i = 0; i<inputIngredients.length; i++){
ingredientString += inputIngredients[i] + ",";
}
var api = "http://www.recipepuppy.com/api/?i=" + inputIngredients + "";
console.log(api);
console.log("inputingredients", inputIngredients);
request.get(api, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
});

I would use Lodash _.forEach method:
https://lodash.com/docs#forEach
var ingredientString = "";
_.forEach(inputIngredients, function(value,key){
if(ingredientString.length != ""){
ingredientString += "," + value;
}
else {
ingredientString = value;
}
});

router.get("/whatCanIMake", function(request, response){
var inputIngredients = request.query;
var ingredientString = "";
console.log(inputIngredients);
//for (var i = 0; i<inputIngredients.length; i++){
// ingredientString += inputIngredients[i] + ",";
//}
for (var property in inputIngredients)
{
if (inputIngredients.hasOwnProperty(property)) {
ingredientString += property + ",";
}
}
//rest of your code here

Related

TypeError: Cannot find function forEach in object in Google App Script

I keep running to Cannot find function for each in object error while trying to loop entries. Is there something I am not seeing?. Here the code. This code is supposed to fetch time data from a system via API do calculations and send email
function getTime() {
var range = [5323, 9626, 4998];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token'
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + range[i] + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
time_entries.forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
submitted_time_entries.forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
//send mail
}
});
}
}
response.data is probably not the array you expect. The server may be returning an error or a successful response that isn't parseable as an array. To find out, print response.data to the console and confirm it's the array you expect.
Seems my API returned an object. I figured out the way around it by using Object.keys method and it worked. Here is the working code.
function getTime() {
var range = [53, 926, 8098];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token';
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + '449625' + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
Object.keys(time_entries).forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
Object.keys(submitted_time_entries).forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
Logger.log(time_entry)
//send mail
}
});
}
}

Move coordinates from json to link (js)

I have js code to get data from back endю
Here is code:
var speeddata = [];
function getSpeedData() {
var googleurl =
"https://roads.googleapis.com/v1/speedLimits?path=50.72389,3.32214|51.72389,3.32214&key=8IAceOk43NpWKpczMAzN5dVosUI=";
$.getJSON(googleurl, function (data, status) {
speedlimits = data;
console.log(speedlimits);
});
var url = $('#getData').data('request-url');
$.getJSON(url,
function (data) {
speeddata = data;
console.log(speeddata);
});
}
Here is what I get
I need to push those coordinates to url to this segment path=50.72389,3.32214|51.72389,3.32214
How I can do this, via js?
You can try this:
var speeddata = [{Latitude2: 51.72389,Longitude2: 3.32214, Speed: 41},{Latitude2: 51.72389,Longitude2: 3.32214, Speed: 41}];
var args = 'yourpath = ';
for(var i=0; i < speeddata.length; i++){
args += speeddata[i].Latitude2 + ',' + speeddata[i].Longitude2;
if(speeddata.length == (i+1)){
break;
}else{
args += '|';
}
}
console.log(args);

How to populate array with results from a series of async requests

So I'm trying to get the names and scores that are in 2 arrays player_name and player_mmr. Calling both with player_name[i] and player_mmr[i] in the fillplayer function just returns undefined. I feel like I'm missing something obvious here but for the life of me can't figure it out. I'm guessing it has to do with the use of push.
var btnmatch = document.querySelector('#get-data');
var btnchat = document.querySelector('#get-chat');
var matchid = document.querySelector('#match-id');
var tableheaders = [
'Hero',
'level',
'Name',
'Kills',
'Deaths',
'assists',
'GPM',
'XPM',
'HD',
'TD'
];
var dataheaders = [
"hero_id",
'level',
'personaname',
'kills',
'deaths',
'assists',
'gold_per_min',
'xp_per_min',
'hero_damage',
'tower_damage'
];
var playerids = [
'player1',
'player2',
'player3',
'player4',
'player5',
'player6',
'player7',
'player8',
'player9',
'player10'
];
var playeraccounts = [];
var requests = [];
var playersdata = [];
var player_name = [];
var player_mmr = [];
btnmatch.addEventListener('click', function () {
GetMatchData(matchid.value);
});
btnchat.addEventListener('click', function () {
for (i in playeraccounts) {
requests[i] = new GetPlayerData(playeraccounts[i]);
}
console.log(player_name);
console.log(typeof player_name);
console.log(player_mmr);
fillplayer();
});
function GetPlayerData(accountid) {
var Url = 'https://api.opendota.com/api/players/' + accountid;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", Url, true);
xmlHttp.onreadystatechange = function ProcessRequestPlayer() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (xmlHttp.responseText == "Not found") {
console.log("not found");
} else {
var info = xmlHttp.responseText;
var playerjson = JSON.parse(info);
player_name.push(playerjson.profile.personaname);
if (playerjson.solo_competitive_rank === null) {
player_mmr.push(playerjson.mmr_estimate.estimate);
} else {
player_mmr.push(playerjson.solo_competitive_rank);
}
}
}
};
xmlHttp.send();
}
function GetMatchData(id) {
var Url = 'https://api.opendota.com/api/matches/' + id;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", Url, true);
xmlHttp.onreadystatechange = function ProcessRequestMatch() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (xmlHttp.responseText == "Not found") {
console.log("not found")
} else {
var info = xmlHttp.responseText;
var testjson = JSON.parse(info);
createTable2(testjson);
getaccountids(testjson);
}
}
};
xmlHttp.send();
}
function getaccountids(json) {
Object.keys(json.players).forEach(function (i) {
playeraccounts.push(json.players[i].account_id);
});
}
function fillplayer() {
console.log(player_name);
console.log(player_mmr);
for (var i = 0; i < playerids.length; i++) {
console.log(player_name[i]);
document.getElementById(playerids[i]).getElementsByClassName('name')[0].innerHTML = player_name + ': ';
document.getElementById(playerids[i]).getElementsByClassName('mmr')[0].innerHTML = player_mmr[i];
}
}
function createTable2(json) {
// Create table.
var table = "<table class='game-table'>";
table += "<thead>";
table += "<tr>";
for (var i = 0; i < 10; i++) {
table += "<th>" + tableheaders[i] + "</th>";
}
table += "</tr>";
table += "</thead>";
table += "<tbody>";
for (var i = 0; i < 5; i++) {
table += "<tr class='radiant'>";
for (var x = 0; x < dataheaders.length; x++) {
table += "<td>" + json.players[i][dataheaders[x]] + "</td>";
}
table += "</tr>";
}
for (var i = 5; i < 10; i++) {
table += "<tr class='dire'>";
for (var x = 0; x < dataheaders.length; x++) {
table += "<td>" + json.players[i][dataheaders[x]] + "</td>";
}
table += "</tr>";
}
table += "</tbody>";
table += "</table>";
var sectie = document.getElementById('table');
if (json.radiant_win == false) {
var winnertekst = document.createTextNode('Dire Victory');
} else {
var winnertekst = document.createTextNode('Radiant Victory');
}
console.log(table);
console.log(typeof table);
console.log(sectie);
document.getElementsByClassName('winnersect')[0].appendChild(winnertekst);
sectie.innerHTML = table;
}
As marekful said you could use promises or you could take a look to Async Functions
and if you're not targeting IE as a browser, you could use the
Fetch API
instead of XMLHttpRequest and have a cleaner structure. Both of these two return a promise that you can consume.
One more source that's showing how you can combine fetch and async functions
JavaScript Fetch API and using Async/Await .

API Call in for loop

I'm working on using Twitch's API (from an alternate link because of CORS). The html comes back empty when this is ran. Is it because of the callback and what can I do to get the data? I can confirm that the link works and have tried stepping through it with no luck.
let usernames = ['freecodecamp'];
let api = '';
let html = '';
for(let i = 0; i < usernames.length; i++) {
api = 'https://wind-bow.gomix.me/twitch-api/streams/' + usernames[i] + '?callback=?';
$.getJSON(api, function(data) {
let online = data.stream == null;
if(online) {
html += usernames[i] + '\nStatus: Offline';
}
else {
html += usernames[i] + '\nStatus: Online';
}
});
}
if(html != '') {
$('#data_display').html('<h1>' + html + '</h1>');
}
Put your last append html block inside the getJSON :
$.getJSON(api, function(data) {
let online = data.stream == null;
if(online) {
html = usernames[i] + '\nStatus: Offline';
}
else {
html = usernames[i] + '\nStatus: Online';
}
$('#data_display').append('<h1>' + html + '</h1>');
});
And also use .append instead of .html , otherwise it will replace the html inside of #data_display.
There is no need to do html += ....
I think javascript promise will help with your situation, take jQuery deferred API as an example:
function fetchUserStatus(username) {
var defer = jQuery.Deferred();
var api = 'https://wind-bow.gomix.me/twitch-api/streams/' + username + '?callback=?';
$.getJSON(api, function(data) {
let online = data.stream == null;
if (online) {
defer.resolve('Offline');
} else {
defer.resolve('Online');
}
});
return defer.promise();
}
let usernames = ['freecodecamp'];
let promises = [];
for (let i = 0; i < usernames.length; i++) {
promises.push(fetchUserStatus(usernames[i]));
}
$.when.apply($, promises).then(function() {
let html = '';
for (let i = 0; i < arguments.length; i++) {
html += usernames[i] + '\nStatus: ' + arguments[i];
}
$('#data_display').append('<h1>' + html + '</h1>');
});
The jQuery when does not support passing an array of promises, that's why the apply function is used, and at the then callback, you'll need to use the arguments to refer to all the resolved value from the promises.
Wish this will help.

compressing string in js and save in localStorage

I'm trying to save a HUGE json string in my localStorage but for some reason sometimes it saves it and sometimes not, I thought I should compress it so I took an LZW implementation in js from one of the threads in stackoverflow.
The problem is when I try to localStorage.setItem() the compressed string it gives me an error "Invalid argument", any idea why or what should I do?
Edit:
this is the code I'm using:
// LZW-compress a string
function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
this is the code that calls the compressing algorithm and saves it in LS
LOG("GetMerchantList(): Done");
var SITESVAR = unescape(data)
localStorage.setItem("MYSITES", lzw_encode(SITESVAR)); //this throws error
IWT.BuildMerchantList(SITESVAR);

Categories

Resources