Javascript Date from array - javascript

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]);

Related

Javascript pushing only last entry in for loop to object

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.

Cannot extract hours from mongodb date array

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];
...
}

How to dynamically replace values in string

I'm trying to replace a unkown amount of strings inside a string and save it in a variable.
var wpContent;
var sourceUrlArray = [];
var pageContent = response.d.Content
for (var i = 0; i < sourceUrlArray.length; i++) {
wpContent = pageContent.replace(sourceUrlArray[i].url, sourceUrlArray[i].sourceUrl)
}
pageContent holds the string where i want to replace one or more instances of a string. The old and new values are stored in sourceUrlArray.
The content of the sourceUrlArray is dynamic and can change.
Only the last replacement is made. I know that is has something to do with it overwriting the wpcontent variable, but I can't seem to figure out where I am going wrong here.

Convert string to become variable

I have multiple variables containing JSON as string (received from AJAX).
data.output_data_1234
data.output_data_5678
I convert them to Array:
var outputdataarr = new Array(data.output_data_1234);
This works fine, but how do I add a number to the var name:
var outputdataarr = new Array('data.output_data_'+formid+'');
this one does not work.
formid contains a proper number.
This does not work too:
var outputvar = window['data.output_data_' + formid];
var outputdataarr = new Array(outputvar);
Please help. Thanks.
You probably mean, you need something like this:
var outputdataarr = new Array(data['output_data_'+formid]);
You can only use string in square brackets as an object field identifier. It cannot contain '.'.
UPDATE:
However, you will probably need a loop to fill the whole array, e.g.
var outputdataarr = new Array();
for (var i=1000; i<2000; i++) {
outputdataarr.push(data['output_data_'+formid]);
}
Use [] instead of new Array is better.
var outputdataarr = [];
outputdataarr.push(data['output_data_'+formid]);
//and so on

Array read problem for map of vectors of strings in javascript

I am a newbie in JS. Here is my code and I believe it should work... but it doesn't.
var pop = new Array();
pop['la'] = new Array('nt','gb','te');
pop['sa'] = new Array('nt','gb');
pop['ha'] = new Array('pc','pa');
var _ecpop="la";
for (var i = 0; i < pop[_ecpop].length; i++)
{
document.write(pop[_ecpop][i]);
}
I just do not know any alternate way to have a map of vectors of a string.
Thanks,
Amir.
That's not an Array, but a Javascript Object, containing Arrays in it's properties. You can use Object and Array literals for that. The advantage is that your code looks much cleaner. There are seldom reasons to use new Array or new Object in javascript code (see for example this SO Question).
var pop = {
la: ['nt','gb','te'],
sa: ['nt','gb'],
ha: ['pc','pa']
}
now you can use
for (var i = 0; i < pop.la.length; i++) {
console.log(pop.la[i]);
}
if a property label is stored in a variable (like you _ecpop), you can use bracket notiation to retrieve it's value:
var laArr = pop[_ecpop];
for (var i = 0; i < laArr.length; i++) {
console.log(laArr[i]);
}
The other way around you can assign a label to an Object:
var _ecpop = 'la';
pop[_ecpop] = ['nt','gb','te'];
document.write is not the preferred way to put things on your page. It's better and just as easy to use some element with an id, and write output to it using innerHTML, for example
document.getElementById('myOutput').innerHTML = '[some output here]';
In javascript, an array can only have numeric indexes, if you want to use textual indexes, you should use object instead.
var pop = new Object();
or
var pop = {};
and then:
pop['la'] = new Array('nt','gb','te');
However, as an object is not an array, it has no length member, but just as an array you can use the for..in to go through all of its values.
Using document.write is not a good choice as it only works during the document loading, not after it. Try to use text nodes or innerhtml instead.

Categories