This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 5 years ago.
I`m trying to write a loop that will read through a nested number array.
The JSON file that I`m reading goes like this. each number key represents event dates.
json reference for startdate and end date
enter image description here
I have below javascript code that reads per var i = 1 or j = 1.
I`d like to read through entire nested number from dates and store them somewhere.
$(document).ready(function () {
$.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (data) {
var data = data;
var i = 2;
var obj = data[i].calEvent;
var bingname = obj.eventName;
var j = 1;
var startdate = obj.dates[j].startDateTime;
var time = new Date(startdate);
var starttime = time.getFullYear()+'-' + (time.getMonth()+1) + '-'+time.getDate();
var name = JSON.stringify(bingname);
document.getElementById("bingname").innerHTML = name;
document.getElementById("bingtime").innerHTML = starttime;
var name = firebase.database().ref("/bing").set({
EventName : name,
EventStart : starttime
});
});
});
Now, I should use something of incremental loop for var j. But I'm not sure how.
The problem for me is that json retrieved in obj.dates[j] doesn't seem like an array. I can't seem to read it as list of numbers to read through. Help is much appreciated.
If anyone can even sort this nearest to furthest from today's date that'd be Einstein:)
You will get an array of objects, that includes a callEvent object that has a dates property which is an array with objects with the property's startDateTime and endDateTime.
It will look like following:
[
{
callEvent: {
dates: [
{startDateTime: '', endDateTime: ''},
// more objects with start- and endDateTime
]
}
},
// more callEvent objects..
]
Now your code should loop through the array to get all callEvent objects and loop through all dates objects inside each callEvent.
$(document).ready(function () {
$.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (array) {
// loop through all elements in the array
for (var i = 0; i < array.length; i++) {
// loop through all dates inside the array
for (var j = 0; j < array[i].calEvent.dates.length; j++) {
console.log(array[i].callEvent.dates[j].startDateTime)
console.log(array[i].callEvent.dates[j].endDateTime)
}
}
});
});
Assuming the dates are valid JSON (JSON Validator), then you should just be able to get the data and loop through it:
for (var i=0;i<data.length;++i) {
console.log(data[i].startDateTime);
console.log(data[i].endDateTime);
}
Related
I have the following code to populate a viewData object:
month = 1;
year = 2019;
days = 31;
// data object for return data
var viewData = {
entries: []
};
// temp data stores
var jsonData = {};
var dict = {};
for (var i = 0; i < days; i++) {
var dArr = [year, month, i+1];
var storeDate = dArr.join("-");
dict[storeDate] = 0;
}
for (var j in rows) { // I get rows from a SQL call, it works
var fullString = formatDate(rows[j].EndTime); // this just uses a function to format a date
var theDate = fullString.split(" "); // this get a date in the format YYYY-MM-dd
dict[theDate] = dict[theDate] + rows[j].TotalDuration; // add the current duration to relevant dictionary entry
}
for (var p = 0; p < days; p++) {
// create the date string for dictionary reference
var dArr = [year, month, p+1];
var storeDate = dArr.join("-");
// populate the jsonData object
jsonData['timestamp'] = storeDate;
jsonData['duration'] = dict[storeDate];
// push the jsonData object to the viewData object
console.log('---------------------------');
console.log('Timestamp: ', jsonData['timestamp']);
console.log('Duration: ', jsonData['duration']);
viewData.entries.push(jsonData);
}
So from this code, when I print out the Timestamp and the duration in the for loop, I get the right values (E.g. "timestamp": "2019-01-04, "duration": 0). But, when I resolve and print out the viewData object, I get all entries with the timestamp value of "2019-01-31" and duration "0". These values are related only to the last iteration of the for loop.
Thus, it appears as if all entries in the viewData object are being populated only with the timestamp and duration values of the last iteration of the for look.
Why is this happening? Is there something related to how javascript works that I'm not understanding here?
Check out these two lines
jsonData['timestamp'] = storeDate;
jsonData['duration'] = dict[storeDate];
jsonData['timestamp'] and jsonData['duration'] are specific key-value pairs, and you're writing over them every time you iterate through. Then when you push it in the last line, it's only pushing a reference to the object, not the actual object. console.log doesn't happen quite as synchronously as you'd want, so sometimes by the time it's actually logging, it's only showing the updated object. You could do something like this:
jsonData[p] = {};
jsonData[p].timestamp = storeDate;
jsonData[p].duration = dict[storeDate];
Another option is making jsonData an array that you push a {timestamp, duration} object or [timestamp, duration] array into.
Also, you can turn these two lines
var dArr = [year, month, p+1];
var storeDate = dArr.join("-");
into a single line using a template string
var storeDate = `${year}-${month}-{p+1}`;
viewData.entries.push(jsonData); pushes a reference of the object "jsonData" to the array, not a copy. This means that when you alter the object jsonData, the reference that was pushed to the array will be changed as well.
My array:
[
{
"date":"2018-04-01",
"time":[{"10:00":"12"},{"12:00":"25"}]
},
{
"date":"2018-04-02",
"time":[{"10:00":"12"},{"12:00":"25"}]
},
{
"date":"2018-04-03",
"time":[{"10:00":"12"},{"12:00":"25"}]
}
]
I need to get every date and time. To get this I am using a for loop. But not able to get date and time.
My script:
var slots = req.body.availableSlots;
var count = slots.length;
for(var i=0;i<count;i++){
console.log(slots[i]);
console.log(slots[i].date);
}
When getting date always says undefined.
It seems like req.body.availableSlots is coming as a multidimensional object array.
So full code need to be:-
var slots = req.body.availableSlots;
for(var i=0;i<count;i++){
var sub_array = slots[i];
for(j = 0; j<sub_array.length;j++){
console.log(sub_array[j].date);
}
}
Instead of using jquery library (jQuery.parseJSON()) use javascript inbuilt JSON.parse
var slots = '[{"date":"2018-04-01","time":[{"10:00":"12"},{"12:00":"25"}]},{"date":"2018-04-02","time":[{"10:00":"12"},{"12:00":"25"}]},{"date":"2018-04-03","time":[{"10:00":"12"},{"12:00":"25"}]}]';
slots = JSON.parse(slots);
var count = slots.length;
for(var i=0;i<count;i++){
console.log(slots[i].date);
I am sucessfully getting data in date format into webservice based on NodeJS+MongoDB. But I cant extract hours from it.
This is date looks in MongoDB:
I try to either split the array elements or apply Date.getHours method using forEach loop.
The problem is that when I just console log elements in forEach loop, I can see my comment I wrote in only the last element in array which I suppose means that forEach loop does not go through all the elements in the array.
This is the code:
user.TrainingPlan[req.params.object].time.forEach(function(item, index, array)
{
console.log(user.TrainingPlan[req.params.object].time.toString() + ' xxx');
});
This is the output I get:
I fixed it by splitting date format instead. Here is the code:
var timestamps = user.TrainingPlan[req.params.object].time;
var tlength = timestamps.length;
for(var i=0; i<tlength;i++){
var dateInfo = timestamps[i].toLocaleString()
var splittedData = dateInfo.split(' ');
var yearMonthDay = splittedData[0];
var data2 = yearMonthDay.split('-');
var year = data2[0];
...
}
This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 5 years ago.
i would like to know how to loop all of my sql datas (that i parsed into a json table) into an array, with adding a key to each of them.
I know how i can loop all of the data into an simple string like this :
var dbString ="";
for(i = 0; i < result.response.length; i++)
{
dbString += result.response[i].names;
}
This would just look like this
var dbString = "James Michael Alfred....";
But how can i make this look like this :
var dbString = {"James":1, "Michael":2, "Alfred":3, .....}
Thanks.
It's a really unique demand to organise a list of names like you want, but here it is:
var dbString = {};
var names = result.response;
for(var i = 0; i < names.length; i++){
dbString[names[i]] = i + 1;
}
I have looking into this issue for a while, but have yet to find a suitable answer (most involve switching to setChoiceValues() rather than addressing the "Cannot convert Array to Choice[]" issue with setChoices([])).
While attempting to generate form sections and questions via Google Script, I ran into the issue of not getting my answer selections to go to specific pages based on the user's answer. This appears to be the difference between setChoiceValues() and setChoices([]), with the latter allowing for page navigation as best as I can tell.
However, when attempting to put my array of new choices into setChoices([]), I get the error message "Cannot convert Array to Choice[]". My code works fine otherwise, but I need to use setChoices([]) (it seems) in order to get the page navigation that I want.
How can I loop values into an array or other container and be able to make them appear as a Choices[] object? How can I make something like this work? It seems like it should be much easier than it is, but I cannot see the solution.
Below is a segment of my code that is causing the issue:
//Form - globally accessible
var f = FormApp.openById(f_id);
//Date Iterator
var curr_date = 0;
//Time Iterator
var curr_time = 0;
//Array of Times
var Tchoices = [];
//Setting Time choices per date
while(curr_date < dates.length)
{
Tchoices = [];
curr_time = 0;
//dates is an array of objects with both d's (single date) and t's
// (array of times for that date)
var d = dates[curr_date].d;
var end_break = f.addPageBreakItem().setTitle("Times for " + d);
var f_time = f.addMultipleChoiceItem().setTitle(d);
while(curr_time < dates[curr_date].t.length)
{
end_break = end_break.setGoToPage(FormApp.PageNavigationType.SUBMIT);
Tchoices.push(f_time.createChoice(dates[curr_date].t[curr_time], end_break).getValue());
curr_time++;
}
f_time.setChoices([Tchoices]);
}
There was some minor issues with the building of your MultipleChoise object:
//Form - globally accessible
var f = FormApp.openById('someID');
//Date Iterator
var curr_date = 0;
//Time Iterator
var curr_time = 0;
//Array of Times
var Tchoices = [];
//Setting Time choices per date
while(curr_date < dates.length)
{
Tchoices = [];
curr_time = 0;
//dates is an array of objects with both d's (single date) and t's
// (array of times for that date)
var d = dates[curr_date].d;
var end_break = f.addPageBreakItem().setTitle("Times for " + d);
var f_time = f.addMultipleChoiceItem();
f.addMultipleChoiceItem().setTitle(d);
while(curr_time < dates[curr_date].t.length) //verify this while not sure what you have inside your dates array
{
end_break = end_break.setGoToPage(FormApp.PageNavigationType.SUBMIT);
Tchoices.push(f_time.createChoice(dates[curr_date].t[curr_time])); //You cannot add a pagebreak inside the elements of a choiseItem array
curr_time++;
}
Logger.log(Tchoices);
f_time.setChoices(Tchoices);
}
Check the values for dates[curr_date].t.length inside the Loop I'm not sure how you constructed the array.
You cannot add a pagebreak inside the elements of a choiseItem array