Change Year-month to Month(letter)-year format in JavaScript - javascript

I have a dataset with date format as
var dataset = [{
"monthDate": "2018-05",
"count": 83
},
{
"monthDate": "2018-06",
"count": 23
},.....]
I wish to change this to 'May-18', 'June-18' and so on and pass this data to Highchart Categories. How do I do that?

You could parse the date into a Date object, and then format it with toLocaleDateString. One adjustment is needed at the end, to get the hyphen in the output:
var dataset = [{ "monthDate": "2018-05", "count": 83 }, { "monthDate": "2018-06", "count": 23 }];
var result = dataset.map(o => ({
monthDate: new Date(parseInt(o.monthDate), o.monthDate.slice(-2) - 1)
.toLocaleDateString("en", {month: "long", year: "2-digit"})
.replace(" ", "-"),
count: o.count
}));
console.log(result);

Related

Remove " " from keys when PHP associative array in parsed through json_encode

I am trying to supply some data to a Javascript Function but right now i am unable to convert it to desired format.
The Correct Format that is Working is below.
const eventsArr = [
{
day: 1,
month: 1,
year: 2023,
events: [
{
title: "asdEvent 1 lorem ipsun dolar sit genfa tersd dsad ",
time: "10:00 AM",
}
],
},
{
day: 13,
month: 11,
year: 2022,
events: [
{
title: "Event 2",
time: "11:00 AM",
},
],
},
];
The format is am being able to produce is the following.
const eventsArr = [
{
"day": "18",
"month": "2",
"year": "2023",
"events": [
{
"title": "Feb 18th Event and Updated From Databae",
"time": "05:10"
}
]
}
The Only difference between two javascript objects/arrays is that my version has "" around the keys and the working format does not have "" around the keys.
My Server Side PHP Code where i am using json_encode
$events = [];
foreach($db_data['CalendarEvent'] as $event)
{
$single_event = array(
'day'=>$event->ce_day,
'month'=>$event->ce_month,
'year'=>$event->ce_year,
'events'=>array(
array(
'title'=> $event->ce_title,
'time'=> $event->ce_time_from,
)
)
);
$events[] = $single_event;
}
$db_data['all_events'] = json_encode($events , JSON_PRETTY_PRINT);
Can somebody help me in this? How can i produce the required format (without "" around the keys in javascript). What i am doing wrong?
Thanks in Advance

How to filter JSON data from API by date range in JavaScript

I want to filter the below JSON data by start date and end date, it should return the data between start date and end date, I tried to achieve using below code, but I'm doing wrong something to filter. I'm new to front end technologies like JavaScript. It would be appreciated if someone can correct me what I'm doing wrong here:
The API data is like that seen below
{
"rec_id": 1,
"emp_id": 1,
"date": "Jan 22, 2020",
"time_in": "09:20",
"time_out": "19:56",
"total_hours": 10.6,
"weekday": 4,
"name": "Carlina Dahlberg",
"gender": "Female",
"designation": "Supervisor",
"department": "Production",
"calculate": "",
"basic_salary": 20000,
"per_day_salary": 1000
},
{
"rec_id": 2,
"emp_id": 2,
"date": "Jan 22, 2020",
"time_in": "08:33",
"time_out": "13:16",
"total_hours": 4.72,
"weekday": 4,
"name": "Brenden Greenacre",
"gender": "Male",
"designation": "Executive",
"department": "Marketing",
"calculate": "",
"basic_salary": 25000,
"per_day_salary": 1250
},
This is my code file
async function getData(){
let myData = await fetch("http://34.198.81.140/attendance.json")
.then((respose) => {
return respose.json()
})
.then((data) => {
return data;
});
let startDate ="Feb 1, 2020";
let endDate = "Feb 29, 2020";
let result = myData.filter((data) => {
return data.date >= startDate && data.date <=endDate;
})
console.log(result);
}
getData()
The data get filtered but not as per requirement, please see the screen shot of console output. In the screen shot the Data come from 1 feb to 29 Feb but, the Data from 2 Feb to 9 Feb whole data is skip by filter function.
You can use Urnary (+) operator, with new Date() to create a timestamp, and then you can compare the timestamps to get desired result.
async function getData() {
/*
let myData = await fetch("http://34.198.81.140/attendance.json")
.then((respose) => {
return respose.json()
})
.then((data) => {
return data;
});*/
// For Testing Purposes only (data modified)
let myData = [{
"rec_id": 1,
"emp_id": 1,
"date": "Jan 22, 2020",
"time_in": "09:20",
"time_out": "19:56",
"total_hours": 10.6,
"weekday": 4,
"name": "Carlina Dahlberg",
"gender": "Female",
"designation": "Supervisor",
"department": "Production",
"calculate": "",
"basic_salary": 20000,
"per_day_salary": 1000
},
{
"rec_id": 2,
"emp_id": 2,
"date": "Feb 5, 2020",
"time_in": "08:33",
"time_out": "13:16",
"total_hours": 4.72,
"weekday": 4,
"name": "Brenden Greenacre",
"gender": "Male",
"designation": "Executive",
"department": "Marketing",
"calculate": "",
"basic_salary": 25000,
"per_day_salary": 1250
}
]
let startDate = +new Date("Feb 1, 2020");
let endDate = +new Date("Feb 29, 2020");
let result = myData.filter((data) => {
return +new Date(data.date) >= startDate && +new Date(data.date) <= endDate;
})
console.log(result);
}
getData()
You need to parse the date into something you can compare dates with.
There are a few options in front of you for that.
Rely on Date.Parse(), a bad idea ref. (mdn)
Use an alternative date library. A simple google search should reveal some.
After parsing the date, you can use the same logic that you are currently using.
you can do it through converting the strings of number into numbers. afterwards try comparing them with each other.
You can use JS libraries such as Moment.js or Dayjs as well to get around it.look through their APIs to dispel the snag you got stuck.
You can use the code below, if you decide to use async/await:
async function getData() {
const response = await fetch('http://34.198.81.140/attendance.json')
const myData = await response.json()
let startDate = 'Feb 1, 2020'
let endDate = 'Feb 29, 2020'
let result = myData.filter(data => {
return (
// Convert all date values to javascript dates using new Date(value)
// Get the number of milliseconds using getTime()
// Compare the milliseconds values
new Date(data.date).getTime() >= new Date(startDate).getTime() &&
new Date(data.date).getTime() <= new Date(endDate).getTime()
)
})
console.log(result)
}
getData()

How to add values from multiple JSON object and store the value in another JSON object in Angular 6

I have two different JSON object. One object is empList and other one is holidayList.
I want to add hours from each JSON object.Andthe sum of hours should be pushed to sumHoursList JSON object.I am doing this using Angular6.
I am not getting exactly how to iterate this to get the required result.
Basically I want to add hours from both the datalist of empList , to that want to add hours from holiday list, and the sum value should
append in sumhourlist
Below is my code.
this.empList = [
{
'id': 1,
'name': 'Name1',
datalist: [
{
"date": 1,
"hours": 6
},
{
"date": 2,
"hours": 0
},
{
"date": 3,
"hours": 12
}
]
},
{
'id': 2,
'name': 'Name2',
datalist:[
{
"date": 1,
"hours": 0
},
{
"date": 2,
"hours": 8
},
{
"date": 3,
"hours": 0
}
]
},
];
this.holidayList=[
{
"date": 1,
"hours": 0
},
{
"date": 2,
"hours": 8
},
{
"date": 3,
"hours": 12
}
]
sumHoursList = [
{
"date": 1,
"hours": 6
},
{
"date": 2,
"hours": 16
},
{
"date": 3,
"hours": 24
}
]
Can anyone please help me how to do this.
If I understand you correctly, you need to sum the hour values of all entries with the same date and it's irrelevant in which source they are located.
Basically you could do it like this (not the most efficient way but to give you an idea):
// map sources into a unified data structure
const extractedArraysFromEmpList = emplist.map((entry)=>entry.datalist)
const sources:Array<Array<{
date:number,
hours:number
}>> = [...extractedArraysFromEmpList,holidaylist];
// now reduce the various sources into one summed array
const result = sources.reduce((reducer:Array<{date:number,hours:number}>, singleSourceArray)=>{
singleSourceArray.forEach((item:{date:number,hours:number}) => {
const existingEntry = result.find((summedItem)=>summedItem.date===item.date);
// if a entry with matching date already exists, sum hours
if(existingEntry) existingEntry.hours += item.hours;
// if no entry exists, add it.
else result.push({date:item.date,hours:item.hours})
}
}, [])
// result is sumHoursList
Note that code is untested. But it should give you an idea of how to solve this case.
This is how I understand the question. You want for each date add the hours together. With this loop you emp array can contain a dynamic number of datalists.
let sum = holidayList
empList.forEach((emp) => emp.datalist.forEach((obj, i) => sum[i].hours += obj.hours))
console.log(sum)
// output: [{ date: 1, hours: 6 }, { date: 2, hours: 16 }, { date: 3, hours: 24 }]
Please also note that these are not JSON objects. They are JavaScript objects.

How to compare date in JSON data using jmespath?

I have one JSON data, which contains date like jan 23,2018.
How can I compare JSON data date with the current date?
[
{
"id": "user_1",
"date": "jan 23, 2019"
},
{
"id": "user_2",
"date": "mar 3, 2017"
},
{
"id": "user_3",
"date": "feb 23, 2019"
}
]
How can I get data which has the date is more than current date using jmespath?
const array = [
{
"id": "user_1",
"date": "jan 23, 2019"
},
{
"id": "user_2",
"date": "mar 3, 2017"
},
{
"id": "user_3",
"date": "feb 23, 2019"
}
];
const newArray = array.map((value) => {
value.date = new Date(value.date).getTime();
return value;
});
console.log(newArray);
console.log('current time in milliseconds ', new Date().getTime());
/* array.forEach((value) => {
const date = new Date(value.date);
console.log(date);
}); */
// console.log('current date', new Date());
Loop array and pass date string to new Date() to get date object and then you can compare it to current date.
EDIT: Now you can directly use milisecond to compare the dates.
You can use JMESPath Custom functions to achieve that. You'll need to convert your date to epoch in order to compare the dates because JMESPath doesn't understand date object.
You can refer an example here under Custom function section: https://pypi.org/project/jmespath/
I created my own custom function to check whether a past date has surpassed current time by atleast certain amount of seconds. Here's my code:
from jmespath import functions
import time
class CustomFunctions(functions.Functions):
# the function name should always have a prefix of _func_ for it to be considered
#functions.signature({'types': ['string']}, {'types': ['number']})
def _func_hasTimeThresholdCrossed(self, jobdate, difference):
jobdate = time.strptime(jobdate,'%Y-%m-%dT%H:%M:%S.%fZ')
return time.time() - time.mktime(jobdate) > difference
options = jmespath.Options(custom_functions=CustomFunctions())
jmespath.search("hasTimeThresholdCrossed(createdAt,`1000000`)",{"createdAt":"2019-03-22T10:49:17.342Z"},options=options)

flattening json to csv format

i am trying to convert a json value to a flat csv based on the field that is selected by user . My json looks like
var data = {
"_index": "test",
"_type": "news",
"_source": {
"partnerName": "propertyFile 9",
"relatedSources": "null",
"entityCount": "50",
"Categories": {
"Types": {
"Events": [{
"count": 1,
"term": "Time",
"Time": [{
"term": "Dec 9",
"Dec_9": [{
"count": 1,
"term": "2012"
}]
}]
}, {
"count": 4,
"term": "News",
"News": [{
"term": "Germany",
"Germany": [{
"count": 1,
"term": "Election"
}],
"currency": "Euro (EUR)"
}, {
"term": "Egypt",
"Egypt": [{
"count": 1,
"term": "Revolution"
}]
}]
}]
}
}
}};
Ive been able to collect the values of all occurences and store it as a csv, but I want to save the details from the root itself..
If I select Time, the csv output should look like,
"test", "news", "propertyFile 9","null", "50", "Events": "Time", "Dec 9", "2012"
Is it possible to flatten the json.. I will add the json fiddle link to show where Ive reached with this thing..
http://jsfiddle.net/JHCwM/
Here is an alternative way to flatten an object into key/value pairs, where the key is the complete path of the property.
let data = {
pc: "Future Crew",
retro: {
c64: "Censor Design",
amiga: "Kefrens"
}
};
let flatten = (obj, path = []) => {
return Object.keys(obj).reduce((result, prop) => {
if (typeof obj[prop] !== "object") {
result[path.concat(prop).join(".")] = obj[prop];
return result;
}
return Object.assign(result, flatten(obj[prop], path.concat(prop), result));
}, {});
}
console.log(
flatten(data)
);
Your data value is not a JSON (string) - it's an object. There are many ways to 'flatten' this object, may be this little function might be helpful:
var recMap = function(obj) {
return $.map(obj, function(val) {
return typeof val !== 'object' ? val : recMap(val);
});
}
And here's how it can be used. )
There is a npm lib just for this with a lot of options: https://mircozeiss.com/json2csv/
# Global install so it can be called from anywhere
$ npm install -g json2csv
## Generate CSV file
$ json2csv -i data.json -o out.csv --flatten-objects
Try looking here:
http://www.zachhunter.com/2011/06/json-to-csv/
and here:
How to convert JSON to CSV format and store in a variable
Try the following :
http://codebeautify.org/view/jsonviewer
Use Export to CSV button
Check this out to flatten the Json
// Convert Nested Json to Flat Json
// Check the final json in firebug console.
var fullData = {"data":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0,"Children":[]},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58,"Children":[]},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83,"Children":[]},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71,"Children":[]}]}
var finalData = [];
loopJson(fullData.data);
function loopJson(data) {
$.each(data, function(i, e) {
if (e.Children.length>0) {
var ccd = e.Children;
delete e.Children;
finalData.push(e);
loopJson(ccd);
} else {
delete e.Children;
finalData.push(e);
}
});
}
console.log(finalData);
Here is Js fiddle link http://jsfiddle.net/2nwm43yc/

Categories