Converting JS array UNIX date integers into JS Date objects - javascript

Is there a way to convert UNIX epoch integers (1402079444, etc) in an array into JavaScript Date objects (Date.UTC(2014, 9, 14), etc) using jQuery?
I'm trying to pass a large JSON array generated by PHP to Highmaps.JS, which almost works great however Highmaps expects a Date object and Date objects aren't valid JSON, so I can't generate them with PHP.
jsFiddle of my current setup here: http://jsfiddle.net/dwgLtscm/2/
(The x-axis isn't displaying dates properly because the data isn't in the proper date format).
[{
"name": "Dissolved Oxygen",
"data": [
[1402079444,9]
]
},
{
"name": "Temperature (Water)",
"data": [
[1401291099,9],
[1401862547,12]
]
},
{
"name": "Temperature (Air)",
"data": [
[1401291099,13],
[1401862547,19]
]
},
]

Given the Json object above, I'd try:
array.forEach(function (val) {
val.data = val.data.map(function (datum) {
return [ new Date(datum[0] * 1000), datum[1] ];
}
}
Unless I'm reading it wrong (I'm assuming data[0] is the UTC value).
(Edited based on feedback below, thanks all!)

Related

Wrong results in group_by by month with javascript date objects in node app

I have a problem using javascript date objects in a node app and running queries through postgresql.
I have following data in a csv file (first column: date, second column: amount)
08/08/2022;620,00
01/08/2022;-73,41
01/08/2022;600,00
01/08/2022;-341,36
Since date format is not standard, I convert it manually to a date object:
new Date(year, month, day);
I store it to a postgresql database through the prisma client.
The date field is following type in schema.prisma
model Transaction {
id Int #id #default(autoincrement())
amount Float
date DateTime #db.Date
which corresponds to this migration:
ALTER TABLE "Transaction" ALTER COLUMN "date" SET DATA TYPE DATE;
Once data is stored, it looks like this:
[
{
"id": 9205,
"date": "2022-08-07T22:00:00.000Z",
},
{
"id": 9206,
"amount": -73.41,
"date": "2022-07-31T22:00:00.000Z",
},
{
"id": 9207,
"amount": 600,
"date": "2022-07-31T22:00:00.000Z",
},
{
"id": 9208,
"amount": -341.36,
"date": "2022-07-31T22:00:00.000Z",
}
]
Dates look good, I double-checked running .getMonth, creating the date again in the browser etc.
I try to run a raw query with prisma:
const expensesByMonths: any[] = await this.prisma.$queryRaw`
SELECT
date_trunc('month', date) as date_month,
sum(amount)
FROM "public"."Transaction"
GROUP BY
date_month
`;
Unfortunately, the results are wrong:
{
"expensesByMonths": [
{
"date_month": "2022-07-01T00:00:00.000Z",
"sum": -414.77
}
],
"incomesByMonths": [
{
"date_month": "2022-07-01T00:00:00.000Z",
"sum": 600
},
{
"date_month": "2022-08-01T00:00:00.000Z",
"sum": 620
}
]
}
I don't understand why group_by from postgresql is not understanding the javascript date objects, since they are strings at the end.
I guess I can't store in postgresql things like 2022-07-31T22:00:00.000Z, I see everywhere dates like '2022-11-23', not sure if it's stored as strings or dates

Get info from Array then Object in Javascript

I'm trying to display data after a Fetch. I grouped this data by date so I grouped my objects into an array which have the date as main key.
But now, I'm kind of lost and don't know how to display get the date as Header section then the objects.
This is my data:
"31 janvier 2015": Array [
Object {
"image": "image",
"name": "name",
},
Object {
"image": "image",
"name": "name",
},
],
"02 février 2016": Array [
Object {
"image": "image",
"name": "name",
},
Object {
"image": "image",
"name": "name",
},
]
What I would like to do is to display it like a section list :
31 janvier 2015
> object
> object
02 février 2016
> object
> object
I think I can map the objects but first I have to get the date and go inside that array.
What you have is an associative array, that is an array that instead of numeric indexes has strings. It works just like an object would if you were for example to do person['age'] on a person object.
You can loop through the "indexes" with the below code, checking hasOwnProperty to avoid any inherited properties. You can then access your dates by key
for (var key in MainArray) {
if (MainArray.hasOwnProperty(key))
console.log(MainArray[key]);
}
Iterate over the map keys, displaying the date and listing the items.
for(let date in list){
// Date as SECTION HEADING
console.log(date);
// access items...
const items = list[date];
// Display item
items.forEach(console.log);
}

convert json to javascript object for datables

I want to convert json into a javascript object but i am unable to do so,since i am new.
{"campaigns":{"campDetails":[{"campaign_id":"1012","campaign_name":"RP - Axe Sample (Submit)"}]}}
into
"columns": [
{ "data": {} },
{ "data": "hr.position" },
{ "data": "contact.0" },
{ "data": "contact.1" },
{ "data": "hr.start_date" },
{ "data": "hr.salary" }
]
javascript object format the above is the javasctipt object to another another json. Just avoid the data I needed to know how you parse example
"columns" : [{data:campaigndetails{ _:campaigns }}]
etc is want the out put be like
columns:[
{data:1012}.
{data:RP - Axe Sample (Submit)}
]
but i dont really know the parameters
Check out http://api.jquery.com/jquery.parsejson/ - That has a good API for your task.
Else, check Converting a string to JSON object - Somewhat similar to your problem.
You can use eval to convert any string into json
var str = {"campaigns":{"campDetails":[{"campaign_id":"1012","campaign_name":"RP - Axe Sample (Submit)"}]}};
var obj = eval(str);

What is the correct format of populating a JSON object with a nested array of objects?

I'm trying to create a JSON object with a nested array of JSON objects. What is the correct format of this?
Here is an example what I am trying to create:
{
"reviewCount": 96,
"reviews": [
{"name": "Sean Steinman", "date": "reviewed 2 weeks ago", "reviewContent": "Fantastic Service"},
{"name": "Ryan Lundell", "date": "reviewed in the last week", "reviewContent":"Ask for Scott!"}
]
}
Here is what I have so far:
var reviewObj = {
reviewCount: reviews.length,
reviews: [{name: , date: , reviewContent:}]
}
After I initialize it, I will fill it with a for loop that runs through an existing array of strings.
CLARIFICATION:
The array that I'm using to populate the JSON object is:
[
"\nSean Steinman\nreviewed 2 weeks ago\n Fantastic Service\n",
"\nRyan Lundell\nreviewed in the last week\n Ask for Scott!\n• • •\n"
]
So I'm creating a new array in my for with tmpArr = reviews[i].split('/n');, and then where I'm getting stuck is how to stick that into the JSON object as an object.
First, you're not building a "JSON" object. You're just building an object. It's not JSON until you JSON-encode it. {"name": "bob"} is not JSON, it's an object literal. '{"name": "bob"}', the string, is JSON.
Second, you cannot loop inside an object literal, which is what your second code example seems to indicate you're trying to do. Instead, you need to initialize you reviews property to an empty array, and then loop and append items to the array.
var reviews = [
"\nSean Steinman\nreviewed 2 weeks ago\n Fantastic Service\n",
"\nRyan Lundell\nreviewed in the last week\n Ask for Scott!\n• • •\n"
];
var reviewObj = {
reviewCount: reviews.length,
reviews: []
}
reviews.forEach(function(line) {
var review = line.split("\n");
reviewObj.reviews.push({name: review[0], date: review[1], reviewContent: review[2]});
});

Data Structure for "Date" based data

NOTE: Language i am using is Javascript
I have a an array of objects. Each object has three properties: year, date, title.
For example:
[
{
year: 2013, date: "23/10/2013", title: "Title1"
},
{
year: 2012, date: "4/2/2012", title: "Title2"
}
]
I need to make an efficient data structure from this array such that:
All objects with same year are grouped together, and groups are sorted on the basis of "year"
All objects with same date and title are grouped together. Objects with different dates are sorted.
The data structure should be efficient for reading and traversing (i need to present them in some sort of timeline).
So, you probably want something like this:
var objects = {
"2012":{
"4/2/2012":{
"title1":[
//array of objects
],
"title2":[
//array of objects
],
// etc
},
"5/9/2012":[
"title3":[/*objects*/],
],
},
"2013":{
// etc
}
}
Then you can just access the array of objects them like this:
objects["2012"]["5/9/2012"]["title1"]
So:
objects["year"]["date"]["title"];

Categories