Using JSON.parse() with date fields? - javascript

Let's say you have the following object as a string:
var timecard = {
"name": "Joe",
"time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)"
}
// as string
var stringed = 'var timecard = { "name": "Joe", "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)" }'
and you run JSON.parse(stringed) to parse it into the object. How would you go about having it convert the date into an actual Date object as opposed to a string?
Thanks!

The JSON data format doesn't have a date type, so you have to write the code to transform it into a Date object yourself.
You can pass a reviver function as the second argument to JSON.parse to do that.
function parseDate(k, v) {
if (k === "time") {
return new Date(v);
}
return v;
}
var json = '{ "name": "Joe", "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)" }';
var data = JSON.parse(json, parseDate);
console.log(data);

Related

Javascript array of multiple object

How to convert the 1 object with multiple item inside to an array of object? please see the picture below to understand what i meant, thanks
var author = (`SELECT author, title, remarks, status, date FROM Transaction`, 1000, data=>{
let obj = {[author: [], book: [], condition: [], status: [], date: []]}
for(let x = 0; x < data.length; x++){
obj.author.push(data[x][0]);
obj.book.push(data[x][1]);
obj.condition.push(data[x][2]);
obj.status.push(data[x][3]);
obj.date.push(data[x][4]);
}
console.log("obj: ", obj)
return resolve(obj);
})
The Current result of console.log("obj: ", obj)
{
"authors": "testuser,testname",
"books": "440936785,440936694",
"conditions": "Very Good,New,",
"status": "Not Available,Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time),Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
What I want result:
{
"authors": "testname",
"books": "440936694",
"conditions": "New",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time)"
},
{
"authors": "testname",
"books": "440936694",
"conditions": "New,",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
You have a list of rows and want to create a list of objects. That means you have to convert every row to an object. Such a transformation is typically done with Array#map, which applies a function to every element in an array a produces a new array from the return value of that function:
const objects = data.map(row => ({
author: row[0],
book: row[1],
condition: row[2],
status: row[3],
date: row[4],
}));
The library you are using to query the database might also be able to already create an object per row (using the column names) so you don't have to do the mapping yourself.

How to get date type value from object?

I want to get all the values from an object whose data type is a date.
How does that possible. And also after that, I want to convert it into UTC and save it.
e.g.
{
employeeid: "4",
id: 276,
birthdate: "Thu Mar 26 2020 05:30:00 GMT+0530 (India Standard Time)",
status: "pending"
}
From this object I just want birthdate(I won't be knowing the property name it can be anything). I want to make this code generic because the variable name varies and I want to use this for the whole application.
You can parse a string as a date. If the string is a valid date then it returns a number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC, otherwise, it returns NaN.
/**
* Check if the string is a valid date string or not.
* For that we check if the given string is really a string, not a number.
* Because a number is parsed as a date by Date.parse()
*/
function isDate(str) {
let date = Date.parse(str);
return (typeof str === 'object' && str instanceof Date) || (typeof str === 'string' && isNaN(+str) && !isNaN(date));
}
/**
* These are some examples
*
*/
let dateString = "Thu Mar 26 2020 05:30:00 GMT+0530 (India Standard Time)";
let nonDateString = "Hello world";
let object = {
employeeid: "4",
id: 276,
birthdate: "Thu Mar 26 2020 05:30:00 GMT+0530 (India Standard Time)",
status: "pending"
};
console.log('Date string: ', isDate(dateString));
console.log('Non date string:', isDate(nonDateString));
// Check a date object rather than a date string. It works for it as well.
console.log('Date object:', isDate(new Date()));
if (isDate(object.birthdate)) {
console.log(`${object.birthdate}: is a date string.`);
} else {
console.log(`${object.birthdate}: is not a date string.`);
}
.as-console-wrapper{min-height: 100%!important; top: 0;}
Update
For your changed query I am updating this answer. As you need all the values of the object with date strings so for that I am generating a new object with all the dates and converts the date strings to UTC string.
/**
* Check if a string is a date or not.
*/
function isDate(str) {
let date = Date.parse(str);
return (typeof str === 'object' && str instanceof Date) || (typeof str === 'string' && isNaN(+str) && !isNaN(date));
}
const obj = {
employeeid: "4",
id: 276,
birthdate: "Thu Mar 26 2020 05:30:00 GMT+0530 (India Standard Time)",
status: "pending",
join: Date('2020-01-12')
};
/**
* This will makes a new object with the date types
* and also convert the date into a UTC string.
*/
const dates = Object.entries(obj).reduce((a, [key, value]) => {
return isDate(value) ? {...a, [key]: new Date(value).toUTCString()} : a;
}, {});
console.log(dates);
.as-console-wrapper {min-height: 100%!important; top: 0;}
You can use instanceof and typeof to check data type.
I made an demo to check your data type
export class AppComponent {
name = "Angular";
mydata = {
employeeid: "4",
id: 276,
birthdate: "Thu Mar 26 2020 05:30:00 GMT+0530 (India Standard Time)",
status: "pending"
};
birthdayType: any;
realType: any;
constructor() {
let dob: any = this.mydata.birthdate;
this.birthdayType = dob instanceof Date;
this.realType = typeof dob;
}
}
export class Data {
public employeeid: string;
public id: number;
public birthday: Date;
public status: string;
}
Stackbliz: https://stackblitz.com/edit/angular-bw4b8d

JavaScript: Return associative array instead of common array

I'm referring to this answer again.
var firstEvents = events.reduce(function(ar, e) {
var id = e.getId();
if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
}
return ar;
}, []);
What do I have to change to get an array with the event titles (Strings) as keys and the start dates (Date objects) as values so I can retrieve a certain start date (Date object) via firstEvents['some event title']?
EDIT:
Current Ouput:
firstEvents = [{eventTitle=Event title 1, eventId=xyz1#google.com, startDate=Sun Mar 18 00:00:00 GMT+01:00 2018, endDate=Mon Mar 19 00:00:00 GMT+01:00 2018},
{eventTitle=Event title 2, eventId=xyz2#google.com, startDate=Tue Mar 19 00:00:00 GMT+01:00 2019, endDate=Wed Mar 20 00:00:00 GMT+01:00 2019},
{eventTitle=Event title 3, eventId=xyz3#google.com, startDate=Fri Mar 20 00:00:00 GMT+01:00 2020, endDate=Sat Mar 21 00:00:00 GMT+01:00 2020}]
Needed Output (Pseudo):
firstEvents = ['Event title 1' => Sun Mar 18 00:00:00 GMT+01:00 2018,
'Event title 2' => Tue Mar 19 00:00:00 GMT+01:00 2019,
'Event title 3' => Fri Mar 20 00:00:00 GMT+01:00 2020]
Do not use push, but set to object with key.
ar = {}; // You may need to change source parameter too
// you cannot change input Array [] to Object {} type inside function
// you can get Array and return Object, but source variable will not change
ar[e.getTitle()] = e.getAllDayStartDate();
Or using some demo data:
var ar = [
{
eventTitle: 'one',
eventId: '#1',
startDate: new Date(),
endDate: new Date()
},
{
eventTitle: 'two',
eventId: 'secondId',
startDate: new Date(),
endDate: new Date()
}];
var retVal = {};
for (var i of ar) {
retVal[i.eventId] = i;
}
console.log(JSON.stringify(retVal, null, 2));
console.log(retVal['#1']);
console.log(retVal.secondId);

How to Update an object in an array

This is my Array
$scope.tooltipsArray = [
{
date: 2018-10-10T07:03:43.835Z,
text: 'name1'
},
{
date: 2018-09-29T18:30:00.000Z,
text: 'name2'
}
];
How can I update date to locale date format like this.
$scope.tooltipsArray = [
{
date: Wed Oct 10 2018 14:05:27 GMT+0530 (India Standard Time),
text: 'name1'
},
{
date: Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time),
text: 'name2'
}
];
I have used map() to do that. But it does not work
var vector = $scope.tooltipsArray.map(function (el) { return new Date(el.date).toLocaleDateString(); });
Can anyone tell me how to do this from map() in JavaScript?
You can use the below code -
$scope.tooltipsArray = [
{
date: "2018-10-10T07:03:43.835Z",
text: 'name1'
},
{
date: "2018-09-29T18:30:00.000Z",
text: 'name2'
}
];
var vector = $scope.tooltipsArray.map(function(el) {return { 'date':new Date(el.date).toString(),'text':el.text}});
console.log(vector);
The output will be like below -
[
{date: "Wed Oct 10 2018 12:33:43 GMT+0530 (India Standard Time)", text: "name1"}
{date: "Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time)", text: "name2"}
]
Why is there a .value key after tooltipsArray?
You assigned the array to tooltipsArray, so unless there's a Proxy involved, expect to access the array through $scope.tooltipsArray.
To fix it, just remove .value.
var vector = $scope.tooltipsArray.map(function (el) { return new Date(el.date).toLocaleDateString(); });
1- Remove .value why is there in the first place?
2- You need to change the date inside the object and then return el instead of date if you just want the date to be changed, likewise:
var vector = $scope.tooltipsArray.map(function(el) {
el.date = new Date(el.date).toLocaleDateString();
return el;
});
What map function does is going through array element one by one and run the callback function, so what you have to do is update the whole object or update one entry
el.date = new Date(el.date).toLocaleDateString();

How to ignore time-zone on new Date()?

I have JavaScript function called updateLatestDate that receive as parameter array of objects.
One of the properties of the object in array is the MeasureDate property of date type.
The function updateLatestDate returns the latest date existing in array.
Here is the function:
function updateLatestDate(sensorsData) {
return new Date(Math.max.apply(null, sensorsData.map(function (e) {
return new Date(e.MeasureDate);
})));
}
And here is the example of parameter that function receive:
[{
"Address": 54,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2009-11-27T18:10:00",
"MeasureValue": -1
},
{
"Address": 26,
"AlertType": 1,
"Area": "West",
"MeasureDate": "2010-15-27T15:15:00",
"MeasureValue": -1
},
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2012-10-27T18:10:00",
"MeasureValue": -1
}]
The function updateLatestDate will return MeasureDate value of last object in the array.
And it will look like that:
var latestDate = Sat Oct 27 2012 21:10:00 GMT+0300 (Jerusalem Daylight Time)
As you can see the time of the returned result is different from the time of the input object.The time changed according to GMT.
But I don't want the time to be changed according to GMT.
The desired result is:
var latestDate = Sat Oct 27 2012 18:10:00
Any idea how can I ignore time zone when date returned from updateLatestDate function?
As Frz Khan pointed, you can use the .toISOString() function when returning the date from your function, but if you're seeking the UTC format, use the .toUTCString(), it would output something like Mon, 18 Apr 2016 18:09:32 GMT
function updateLatestDate(sensorsData) {
return new Date(Math.max.apply(null, sensorsData.map(function (e) {
return new Date(e.MeasureDate).toUTCString();
})));
}
The Date.toISOString() function is what you need
try this:
var d = new Date("2012-10-27T18:10:00");
d.toISOString();
result:
"2012-10-27T18:10:00.000Z"
If you use moment it will be
moment('Sat Oct 27 2012 21:10:00 GMT+0300', 'ddd MMM DD DDDD HH:mm:SS [GMT]ZZ').format('ddd MMM DD YYYY HH:mm:SS')

Categories