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];
...
}
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.
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);
}
I'm working on an add-in for excel 2016 using the javascript API. I can successfully get the range into an array and get the values to show in console.log. I've also been able to get the values into a JSON array using JSON.stringify();
I need to manipulate the array to remove the empty values ("").
Can this be accomplished by using regular javascript array methods?
I'm thinking I can display the results back into a different worksheet using a similar approach like i did with var shWk
Here are some snippets of what I'm trying to do:
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
//document.getElementById("date").innerHTML = Date("MAR 30 2017");
$('#deleteTab').click(deleteTab);
$('#preview').click(preview);
$('#publish').click(publish);
});
};
function preview() {
Excel.run(function(ctx) {
//getting the colname from a date range in B2
var colName = ctx.workbook.worksheets.getItem('preview').getRange("B2");
colName.load('values');
return ctx.sync().then(function() {
//converting colname value to string for column name
var wkN = (colName.values).toString();
// displaying on the task pane
document.getElementById("tst").innerText = wkN;
// testing to confirm i got the correct colname
var shWk = ctx.workbook.worksheets.getItem('preview').getRange("B3");
shWk.values = colName.values;
//building the column connection by setting the table name located on a different worksheet
var tblName = 'PILOT_ZMRP1';
var tblWK = ctx.workbook.tables.getItem(tblName).columns.getItem(wkN);
//loading up tblWK
tblWK.load('values');
return ctx.sync().then(function(){
//this is where my question is:
var arry = tblWK.values;
for (var i=0; i < tblWK.length; i++){
if (tblWK.values !== ""){
arry.values[i][0]) = tblWK.values[i][0]
};
};
console.log(arry.length); //returns 185
console.log (arry.values);//returns undefined
tblWK.values = arry;
var tblWeek = tblWK.values;
console.log(tblWeek.length);//returns 185
console.log(tblWK.values);//returns [object Array] [Array[1],Array[2]
})
});
}).catch(function (error) {
console.log(error);
console.log("debug info: " + JSON.stringify(error.debugInfo));
});
}
What am I missing? Can you point me to some resources for javascript array handling in the specific context of office.js?
I want to thank everyone for the time spent looking at this question. This is my second question ever posted on Stack Overflow. I see that the question was not written as clear as it could've been. What i was trying to achieve was filtering out the values in a 1D array that had "". The data populating the array was from a column in a separate worksheet that had empty values (hence the "") and numeric values in it. the code below resolved my issue.
//using .filter()
var itm = tblWK.values;
function filt(itm){
return itm != "";
}
var arry = [];
var sht = [];
var j=0;
var s=0;
arry.values = tblWK.values.filter(filt);
//then to build the display range to show the values:
for (var i=0; i < itm.length-1; i++) {
if (tblWK.values[i][0]){
var arry; //tblWK.values.splice(i,0); -splice did not work, maybe my syntax was wrong?
console.log("this printed: "+tblWK.values[i][0]);
var cl = ('D'+i); //building the range for display
j++; //increasing the range
s=1;//setting the beignning range
var cll = cl.toString();//getRange() must be a string
console.log(cll);//testing the output
}
}
//using the variable from the for loop
var cl = ('D'+s+':D'+j);
var cll = cl.toString();
console.log(cll);//testing the build string
sht = ctx.workbook.worksheets.getItem('Preview').getRange(cll);
sht.values = arry.values; //displays on the preview tab
console.log (arry.values); //testing the output
The question was probably easier said by asking what vanilla javascript functions does office.js support. I found a lot help reading Building Office Add-ins using Office.js by Micheal Zlatkovsky and by reading the MDN documentation as well as the suggested answer posted here.
Regards,
J
I'm not sure what this check is trying to achieve: tblWK.values !== "". .values is a 2D array and won't ever be "".
For Excel, the value "" means that the cell is empty. In other words, if you want to clear a cell, you assign to "". null value assignment results in no-op.
You can just fetch the values form the array that contains null by using for each and can can push the null values into another array.
I have an array of dates which I am looping through to get each element. the elements are not date objects but strings (I think).
If I display each of the elements to the console I get:
2015,09,19
2015,09,21
I'm trying to turn them into normal dates but I keep getting invalid date. If I statically try
var temp = new Date(2015,09,21);
it works fine but if I do
var temp = new Date(datax[i]);
I get invalid date
full loop below
for (var i = 0; i < datax.length; i++) {
var temp = new Date(datax[i]); // fails says invalid date
//var temp = new Date(2015,09,21); //works fine but is statically assigned (want to get it from array)
console.log(temp);
}
thanks for any help
If content of array is a string like "2015,19,09" for example, go with
new Date(datax[i].replace(/,/g, "-");
It should do it.
I guess "2015,19,09" is not a valid string to be parsed by the date object, but "2015-19-09" will.
Or if you want the same pattern as what you tried manually, first parse the string and make it an array.
var temp = datax[i].split(",");
temp = new Date(temp[0], temp[1], temp[2]);
If the content of the array is itself an array, go for
new Date(datax[i][0], datax[i][1], datax[i][2]);
I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);