I just started working with JSON strings. i have an array of json strings that contains json strings like
{"ID":"3", "LinkFilename":"Test.txt", "Sender":"abc#hotmail.com", "Created":"2014-07-07T20:13:18.000Z"}
what i want to do is to take change the value of "Created" key (which is a date) and omit its time part so it must show only date part. i want to produce something like:
{"ID":"3", "LinkFilename":"Test.txt", "Sender":"abc#hotmail.com", "Created":"2014-07-07"}
The code to produce Json is as follows:
var ItemsEntries = [];
var listItemInfo = '';
var itemsCount = this.collListItem.get_count();
for (i = 0; i < itemsCount; i++) {
var item = this.collListItem.itemAt(i);
var ItemEntry = JSON.stringify(item.get_fieldValues());
ItemsEntries.push(ItemEntry);
listItemInfo += ItemsEntries[i].toString(); + '\n';
}
Please guide me through this.
If you have the Javascript object:
var item = {
"ID":"3",
"LinkFilename":"Test.txt",
"Sender":"abc#hotmail.com",
"Created":"2014-07-07T20:13:18.000Z"
}
and you want to change the Created field in the way you described, you can first create a new Date object out of the Created field value and just extracting the pieces you care about with the functions included in the Date API (http://www.w3schools.com/jsref/jsref_obj_date.asp).
This code should be able to change obj to the format you require:
var formatItem = function(item){
var date = new Date(item["Created"]);
var formattedDate = date.getFullYear()
+ '-'
+ date.getMonth() + 1 // zero-based index...
+ '-'
+ date.getDate();
item["Created"] = formattedDate;
};
One caveat is that the month won't be padded on the left by a 0 if it's a single digit, but that's easy enough to fix on a case-by-case basis.
Related
in my current project I need a Pie Chart in which calculated values should be displayed.
I have now five values as array, which I need to add, so that I have the desired value.
But now I am a bit confused, because no matter if I convert the arrays to sting, or use them directly in the addition, they are always lined up and not added.
What am I missing here?
In a subtraction directly after the calculation works, but here I still have a date value (number of days in the month) in the calculation.
Why does this calculation work?
My Problem
For example I get here "02400" as result and not "6".
var training = training_intervall + training_longrun + training_speedwork + training_stabilisation + training_competition;
My JS function:
function userDiaryMonthTrainingStats(user_id) {
$.ajax({
url: "../diary/includes/training/diary-training-monthly-training-stats.php?user_id=" + user_id,
type: "GET",
success: function(monthly_training_stats) {
var training_intervall = [];
var training_longrun = [];
var training_speedwork = [];
var training_stabilisation = [];
var training_competition = [];
var training_injury = [];
for(var i in monthly_training_stats) {
training_intervall.push(monthly_training_stats[i].training_intervall),
training_longrun.push(monthly_training_stats[i].training_longrun),
training_speedwork.push(monthly_training_stats[i].training_speedwork),
training_stabilisation.push(monthly_training_stats[i].training_stabilisation),
training_competition.push(monthly_training_stats[i].training_competition),
training_injury.push(monthly_training_stats[i].training_injury)
}
var date = new Date();
var month = date.getMonth() + 1;
var year = date.getFullYear();
daysInMonth = new Date(year, month, 0).getDate();
training_intervall = training_intervall.toString();
training_longrun = training_longrun.toString();
training_speedwork = training_speedwork.toString();
training_stabilisation = training_stabilisation.toString();
training_competition = training_competition.toString();
var training = training_intervall + training_longrun + training_speedwork + training_stabilisation + training_competition;
var training_free = daysInMonth - training_intervall - training_longrun - training_speedwork - training_stabilisation - training_competition - training_injury;
var userMonthlyTrainingStatsData = {
datasets: [{
data: [training, training_injury, training_free],
backgroundColor: ['#36a2eb', '#e33b3b', '#4bc07d']
}],
labels: [
'Training',
'Injury',
'Free'
]
};
........
}
})
}
use parseInt() to change from a string to int then you can add the strings as they are now numbers
var training = parseInt(training_intervall) + parseInt(training_longrun) + parseInt(training_speedwork + parseInt(training_stabilisation) + parseInt(training_competition);
if you want the result back to a string simply put after this
training=""+training
Two problems in your code:
training_intervall and the other 4 variables you want to add are arrays, you should iterate them.
The values are strings, using + with strings results in a new concatenated string. To convert easily a string number to a number (example "1" to 1), you can:
const myString = "1"
const myNumber = myString * 1 // myNumber = 1
Recently Attended the interview, Some one asked the question like below:
var array = [0,1,2,3,4,5];
Output :
temp:
temp1:1
temp22:22
temp333:333
temp4444:4444
temp55555:55555
I tried below code it is working fine but is there any best solution for this example :
array.forEach(function(item,index){
var text ="";
if(index >= 2){
for(var j =1; j <= index; j++){
text += index;
}
console.log("temp"+text + ":" + text);
}else{
console.log("temp"+index + ":" + index);
}
});
Thanks in advance!
Using ES6 template strings and String.prototype.repeat
var array = [0,1,2,3,4,5];
array.forEach(item => {
const text = String(item).repeat(item);
console.log(`temp${text}: ${text}`);
})
And the same code translated into ES5 - this will work in all browsers starting from IE9 and above.
var array = [0,1,2,3,4,5];
array.forEach(function(item) {
var text = Array(item+1).join(item);
console.log("temp" + text + ": " + text);
})
Since String.prototype.repeat does not exist in ES5, there is a bit of a hack to generate a string of specific length with repeating characters:
Array(initialCapacity) will create a new array with empty slots equal to what number you pass in, Array.prototype.join can then be used to concatenate all members of the array into a string. The parameter .join takes is the separator you want, so, for example you can do something like this
var joinedArray = ["a","b","c"].join(" | ");
console.log(joinedArray);
However, in this case, each of the members of the array is blank, since the array only has blank slots. So, upon joining, you will get a blank string, unless you specify a separator. You can leverage that to get a repeat functionality, as you are essentially doing something like this
//these produce the same result
var repeatedA = ["","",""].join("a");
var repeatedB = Array(3).join("b");
console.log("'a' repeated:", repeatedA);
console.log("'b' repeated:", repeatedB);
Using the Array function, you can scale it to any number of repeats you want. The only trick is that you need to add 1 when creating the array, since you get one less character when joining.
You could iterate the array and iterate the count. Then display the new string.
var array = [0, 1, 2, 3, 4, 5];
array.forEach(function (a, i) {
var s = '';
while (i--) {
s += a;
}
console.log ('temp' + s + ':' + s);
});
I'm currently a bit stuck trying to combine two arrays (one of dates, one of times).
I've written a PHP script to pass out JSON from an SQL table I have containing the data, but I'm struggling to turn the two arrays into a single datetime array in JavaScript.
The JSON is coming out as:
{
"dates": [
"2016-03-13",
"2016-03-13",
"2016-03-14",
"2016-03-14"
],
"times": [
"16:41:13",
"17:36:57",
"08:53:02",
"21:53:11"
]
}
So far I'm using this to collect the data, though I'm really not sure where to go from there (or if what I'm getting is even an array?):
$(document).ready(function() {
var API_URL = "php_script.php";
$.getJSON(API_URL, function(data) {
var dates = data.dates;
var times = data.times;
console.log(dates + " " + times);
});
});
The output of which is:
2016-03-13,2016-03-13,2016-03-14,2016-03-14,16:41:13,17:36:57,08:53:02,21:53:11
I'd prefer:
[2016-03-13 16:41:13,2016-03-13 17:36:57,2016-03-14 08:53:02,2016-03-14 21:53:11]
To be passed out as an array which I can then use with chart.js.
The dates and times will be used for the X axis and the time between them for the Y axis, so it would be useful to be able to complete some kind of datetime math on the data, if possible.
Here's a way to manually mix them together.... The gist is to manually splice the strings together and then use Date.parse() to make the date objects.
var dates = [
"2016-03-13",
"2016-03-13",
"2016-03-14",
"2016-03-14",
];
var times = [
"16:41:13",
"17:36:57",
"08:53:02",
"21:53:11",
];
var both = [];
for (var i = 0; i < dates.length; i++) {
both.push(new Date(Date.parse(dates[i] + " " + times[i])));
}
console.log("%j",both);
This sort of thing is easy if you use a library like lodash. In this case you would want _.zip
var dates = data.dates;
var times = data.times;
var zipped = _.zip(dates, times);
var text = _.reduce(zipped, function(aggregate, item) { return ',' + item[0] + ' ' + item[1]; });
console.log(text);
try splitting the dates and times with , and concat each of them by using loop
var data = {
"dates": [
"2016-03-13",
"2016-03-13",
"2016-03-14",
"2016-03-14"
],
"times": [
"16:41:13",
"17:36:57",
"08:53:02",
"21:53:11"
]
}
var datetimes = [];
for (var i = 0; i < data.dates.length; i++) {
datetimes.push(data.dates[i] + ' ' + data.times[i]);
}
document.write('<pre>' + JSON.stringify(datetimes, 0, 4) + '</pre>')
I have an array look like:
var v = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"]
What I want to do is sort this dynamically into a new empty array nv. When the sorting is done nv should look like.
var nv = [["07/27/2015", "07/28/2015"], ["08/29/2015", "08/29/2015"], ["07/27/2016"]]
Is it possible to sort like this way?
var dates = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"];
var groupedDates = dates.reduce(function(l, r) {
var keyParts = r.split("/"),
key = keyParts[2] + keyParts[0];
if (typeof l[key] === "undefined") {
l[key] = [];
}
l[key].push(r);
return l;
}, {});
var result = Object.keys(groupedDates)
.sort(function(a, b) { return Number(a) - Number(b); })
.map(function(key) {
return groupedDates[key];
});
console.log(result); // [["07/27/2015","07/28/2015"],["08/29/2015","08/29/2015"],["07/27/2016"]]
fiddle
So I made a function that puts the dates into an object whose properties are month and year. A date is put into the property of its month and year. The function then creates an array and creates an inner array for every property of the function. In each inner array it puts all the dates of that property. I figured this approach would be more efficient than nested for loops.
// function takes an array of dates in the following format MM/DD/YYYY
// outputs an array with inner arrays of dates. Each inner array contains dates of the same month and year
var groupDates = function(dateArray) {
// create object to organize dates by month and year
var dateHash = {};
// the array that is outputted
var groupedDates = [];
//for every date in dateArray
dateArray.forEach(function(currentDate) {
// check if any other dates with the same month and year exist in the dateHash object
if (dateHash[currentDate.substr(0, 2) + currentDate.substr(6)]) {
// if other dates exist, push the date to the array in the dateHash property for the dates current month and year
dateHash[currentDate.substr(0, 2) + currentDate.substr(6)].push(currentDate);
} else {
// otherwise create a property for the dates month and year and store the current date in an array in the propery
dateHash[currentDate.substr(0, 2) + currentDate.substr(6)] = [currentDate];
}
});
// for every propery in the datehash, push the array of dates into the grouped dates array
for (var dateGroup in dateHash) {
groupedDates.push(dateHash[dateGroup]);
}
return groupedDates;
};
var dateArray = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"];
console.log(groupDates(dateArray));
You can loop over the array and check for each value if it has a new month and year, or it's already included in the sorted array. I think like this untested code:
new_arr = new Array();
for(var i=0; i < v.length; i++){
var this_date = new Date(v[i]);
var month_and_year = this_date.getMonth() + this_date.getFullYear();
if(typeof(new_arr[month_and_year]) == 'undefined'){
new_arr[month_and_year] = new Array();
}
new_arr[month_and_year].push(v[i])
}
I have a myDate variable with the value 18-Nov-2013.Each day its value is being changed.Tommorow this myDate variable will have the value 19-Nov-2013.I have a list of values that i have mapped into a single array named exclude which contains some dates that are to be excluded ,now it has values ["20-Nov-2013",21-Nov-2013", "23-Nov-2010"] .How could i filter my value from the list of values from the exclude array.I need the next highest value from the array.So here i need the value 22-Nov-2013 after tommorrows date.Could someone help me with this.
var excluded = ["30-Nov-2013","01-Dec-2013","02-Dec-2013"];
var myDate = "29-Nov-2013";
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var current = new Date(myDate);
while(true){
current = new Date((current.getDate()+1<10? "0"+(current.getDate()+1):(current.getDate()+1))+ "-" + month[current.getMonth()] + "-" + current.getFullYear());
var checkDate = (current.getDate()<10? "0"+(current.getDate()):(current.getDate()))+ "-" + month[current.getMonth()] + "-" + current.getFullYear();//this is necessary for when the +1 on day of month passes the month barrier
if(-1 == excluded.indexOf(checkDate))
break;
}
alert(checkDate);
I don't know if this is the best approach, or if is the best algorithm, but you may try this:
var myDate = ["17-Nov-2013", "18-Nov-2013"];
var excluded = ["20-Nov-2013", "21-Nov-2013", "23-Nov-2013"];
var months = {"Nov": 10}; // Add others months "Jan": 1, "Fev": 2 etc...
function findExcluded(date)
{
for (var i = 0; i < excluded.length; i++)
{
if (excluded[i] === date)
{
return true;
}
}
return false;
}
function nextDate()
{
var last = myDate[(myDate.length - 1)];
var s = last.split("-");
var d = new Date(s[2], months[s[1]], s[0]);
var next = new Date(d);
var chkDate = "";
do
{
next.setDate(next.getDate() + 1);
chkDate = next.getDate() + "-" + findMonth(next.getMonth()) + "-" + next.getFullYear();
} while(findExcluded(chkDate));
return chkDate;
}
function findMonth(m)
{
var i = 10; // When you fill all months on 'months' array, this variable should start at '0' in order to loop to works.
for (var month in months)
{
if (i == m)
{
return month;
}
i++;
}
}
var nd = nextDate();
alert(nd);
See it woring here.
No code ? Well here will be my method:
1.Get next date for mydate. Say that is var nextDate.
2.Check whether that date exist in the array.
3.If exists add one more day to nextDate. Again check in the array.
4.Do it until you get a date which is not present in your exclude array
For checking whether it exists in the array you can use arrValues.indexOf(nextDateInProperFormat) > -1