I'm trying to make a function that iterates through all the objects in an array returned to me by the server. Here's the structure that is listed when I console.log my response.
Now I made a javascript function that looks like this—
var createPosts = ((data) => {
var postsArrayLength = data.response.total_posts;
for ( i = 0; i < postsArrayLength; i++ ) {
//for each post create a div
var postDiv = document.createElement('div');
postDiv.className = 'post ' + data.response.posts.postsArrayLength[i].type;
}
});
and I'm receiving this error—
Uncaught TypeError: Cannot read property '0' of undefined
It seems to only be giving me this error when I try to get an object that has an integer as its name.
Is there a way to deal with this? Or am I going about this completely wrong? Thanks!
Rewrite your function to something like this:
var createPosts = data => {
for ( i = 0; i < data.response.posts.length; i++ ) {
//for each post create a div
var postDiv = document.createElement('div');
postDiv.className = 'post ' + data.response.posts[i].type;
}
};
Related
This problem is very annoying. So, I am making a scheduled trigger run every 24 hours. It simply gets items from one collection does some data processing then appends information to another collection. The functioning code works even when the function runs. But it will not let me save because there are "runtime" errors? Even though it was executed perfectly and returned.
Console Error
> result (JavaScript):
EJSON.parse('{"$undefined":true}')
I suppose this has something to do with returning. but when I return null I get this:
> result:
null
> result (JavaScript):
EJSON.parse('null')
when trying to save I get this at the top of the page:
runtime error during function validation
Function Code:
exports = async function() {
const usersCol = context.services.get("SchoologyDashCluster").db("SchoologyDashApp").collection("users");
const gradesCol = context.services.get("SchoologyDashCluster").db("SchoologyDashApp").collection("grades");
var usersCusor = await usersCol.find( ).toArray();
var gradesCusor = await gradesCol.find( ).toArray();
let insert = [];
for (let i = 0; i < usersCusor.length; i++) {
var user = usersCusor[i];
var userSavedGrades = gradesCusor[i].grades
var currentGrades = await getGrades(user.schoologyUID, user.consumerKey, user.secretKey);
var lastGraded = NaN;
let index = gradesCusor[i].grades.length - 1;
while (true) {
if (gradesCusor[i].grades[index].changed == 1) {
lastGraded = index;
break
}
index = index - 1;
}
console.log(lastGraded)
if (userSavedGrades[lastGraded].grades.ga == currentGrades.ga){
currentGrades = { changed : 0, time: new Date().getTime()};
} else {
currentGrades = {changed : 1, grades: currentGrades, time : new Date().getTime()};
}
gradesCol.updateOne(
{"user" : user._id},
{"$push" : {"grades" : currentGrades}}
)
}
// return usersCol.find( );
return null;
};
The answer was simple and now I feel ignorant. Instinctual I put the module imports at the top of the document. However this is incorrect and they need to be placed in the exports function, like so:
exports = function (x,y,z) {
const http = context.http;
return;
}
I'm trying to count the number of misbehavior on the two routes I've made in my database. Below are the structure of my firebase database under drivers and reports database respectively:
[drivers database] - i.stack.imgur.com/Q6GKs.png
[reports database] - i.stack.imgur.com/ALWPu.png
Here's my counter for counting the number of misbehavior:
<script>
var route1Count = 0;
var route2Count = 0;
var drivers;
var reports;
var driversRef = firebase.database().ref('drivers/');
var reportsRef = firebase.database().ref('reports/');
driversRef.once('value', (snapshot) => {
drivers = snapshot;
});
reportsRef.once('value', (snapshot) => {
reports = snapshot;
});
drivers.forEach((driver) => {
var violationCount = reports.filter((report) => report.val().plateNumber === driver.key).length;
if(driver.val().route === "Fairview - Quiapo"){
route1Count += violationCount;
}else if(driver.val().route === "Quiapo - Fairview"){
route2Count += violationCount;
}
});
document.getElementById("demo").innerHTML = "route1: " + route1Count + "route2: " + route2Count;
</script>
I get this error message:
Uncaught TypeError: Cannot read property 'forEach' of undefined
at drivers.forEach, all inputs will be greatly appreciated! Thanks!
Error Message :
you could nest them, or if you run this in an environment that supports es6's Promise object (which your code suggests), you could use the once() returning a promise and more elegantly do:
Promise.all([driversRef.once('value'), reportsRef.once('value')])
.then(([driversSnapshot, reportsSnapshot]) => {
// ...
})
I am attempting to pull information from the League of Legends API.
To simplify what I am doing, I am attempting to pull information about a user and their previous matches. The problem that I run into is that when I parse a JSON request, it returns a champion ID rather than their name (Ex: 412 rather than "Thresh").
The only solution I can see for this would be to make another JSON request and parse that data for the champion name. Currently what I have looks like this.
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json2.name;
});
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
}
});
I'm unable to access the champName variable due to it being nested within the second JSON function.
Is there a better way to do this?
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json2.name;
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
});
}
});
Just put it inside the second json request since you need to wait till that request is done anyway.
You should put the append statement in the callback because getJSON is an asynchronous method (does mean the Request is running in the background, and calls your function back when it got a response), so you should wait for the response first then you can append it to #champ :
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json.name;
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
});
}
});
Hope this helps.
So I have a list of about 200 rows in my Parse Core. I am trying to create a job that runs through the entire list and changes the entire column of push to 0. I am trying to do so with this code:
Parse.Cloud.job("SetPush", function(request, response) {
//take in JSON with dict
var newts = new Array();
for ( var i = 0; i < request.params.push.length; i++ )
{
//add these entries to db
var DataClass = Parse.Object.extend("AllTeams");
var dataupdate = new DataClass();
var origdata = request.params.datalist[i];
dataupdate.set("push", "0");
newts[i]=dataupdate; //add another item to list
}
Parse.Object.saveAll(newts,{
success: function(list) {
// All the objects were saved.
response.success("ok " ); //saveAll is now finished and we can properly exit with confidence :-)
},
error: function(error) {
// An error occurred while saving one of the objects.
response.error("failure on saving list ");
},
});
//default body does not do response.success or response.error
});
As you can see my class is SetPush and I want to update the push column all the way down. The problem I believe lies in this:
for ( var i = 0; i < request.params.push.length; i++ )
When I run this code in the Cloud Code, it returns this error:
'TypeError: Cannot read property 'length' of undefined at main.js:43:60'
What am I doing wrong? Thank you
.length is undefined because request.params.push is an object. Looks like you want to iterate through a list you're passing in to this cloud function using the input parameter request.params.push, if/assuming the caller is passing in a valid JSON as 'push' then you can do something like this
Parse.Cloud.job("SetPush", function(request, response) {
//take in JSON with dict
var parsedJson = JSON.parse( request.params.push );
var newts = new Array();
for ( var i = 0; i < parsedJson.length; i++ )
{
//add these entries to db
var DataClass = Parse.Object.extend("AllTeams");
var dataupdate = new DataClass();
var origdata = request.params.datalist[i];
dataupdate.set("push", "0");
newts[i]=dataupdate; //add another item to list
}
Parse.Object.saveAll(newts,{
success: function(list) {
// All the objects were saved.
response.success("ok " );
//saveAll is now finished and we can properly exit with confidence :-)
},
error: function(error) {
// An error occurred while saving one of the objects.
response.error("failure on saving list ");
},
}); //default body does not do response.success or response.error
});
I am trying to read the parameters value from req.params but in a different way (I am trying to make an API in RESTIFY).
First I read the keys that are available in req.params, like;
var requestData = Object.keys(request.params);
And than I loop through each key and try to fetch its value. below is the code;
for(i = 1; i < requestData.length; i++) {
keyValue = requestData[i];
console.log(request.params.keyValue);
}
But the output shows me UNDEFINED.
Reason: I am trying to read the parameters this way because, then, I do not need to know the name of each parameter.
Below is the complete code:
var restify = require('restify');
var assert = require('assert');
var server = restify.createServer();
var client = restify.createStringClient({
url: 'http://example.com'
});
function onRequest(request, response, next)
{
console.log(request.params);
var requestData = Object.keys(request.params);
var customJsonString = '';
var keyValue = '';
for(i = 1; i < requestData.length; i++) {
keyValue = requestData[i];
console.log(request.params.keyValue);
customJsonString += "" + requestData[i] + " : " + requestData[i] + ", ";
}
console.log(customJsonString);
}
function start()
{
server.use(restify.fullResponse()).use(restify.bodyParser());
server.get(/^\/(.*)/, onRequest);
server.post(/^\/(.*)/, onRequest);
server.listen(8888);
console.log("Server has started.");
}
exports.start = start;
I will really appreciate any help regarding this issue.
Try this instead:
console.log(request.params[keyValue]);
request.params.keyValue means Give me the value of the property keyValue, whereas the code above means Give me the value of the property whose name is stored in the variable keyValue.
Also, are you sure you want to start with i = 1? Javascript-arrays are 0-based, so I think you want i = 0 instead.
It could help if you can give us the URL you are testing right now as well as the console output your get.
However, please note that arrays in Javascript have 0 based index and your loop should look like this:
for(var i = 0; i < requestData.length; i++) {
}
To loop through the properties of an object, you should probably use for..in anyway:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
I don't know if that will solve your problem but it's a start.