I am trying to get the count from JSON response which has current date in the key.
Json Response:
[
{
"type": {
"id": "mobile",
"name": "mobile",
"description": "",
"total_count": 0
},
"counts": [
{
"date": "2018-09-06",
"timestamp": 1536192000000,
"count": 20
},
{
"date": "2018-09-07",
"timestamp": 1536278400000,
"count": 10
}
]
},
{
"type": {
"id": "lap",
"name": "lap",
"description": "",
"total_count": 0
},
"counts": [
{
"date": "2018-09-06",
"timestamp": 1536192000000,
"count": 19
},
{
"date": "2018-09-07",
"timestamp": 1536278400000,
"count": 20
}
]
}
]
My New try as per vikscool code:
var json_count = JSON.parse(getcounts);
var curDate = getCurrentDate();
var mobilcount = () => json_count.map(ct => {
const count = ct.counts;
const getDate = count.find(dt => dt.date === curDate);
window.alert('count is ', getDate.count);
return {getDate};
});
mobilcount();
function getCurrentDate () {
var nowDate = new Date();
var month = (nowDate.getMonth() + 1).toString().length == 1
? '0' + (nowDate.getMonth() + 1)
: (nowDate.getMonth() + 1);
var day = nowDate.getDate().toString().length == 1
? '0' + nowDate.getDate()
: +nowDate.getDate();
return nowDate.getFullYear() + '-' + month + '-' + day;
}
output: "count is "
but there is no count printed from json.
Is there any solution in Javascript I can get the current date and get the counts.
I need to get the count as 10 in mobilcount.
As the dates are stored in the JSON Array key named as the counts of the first object of the json_count you can not fetch it using:
var instance_count=json_count[0].values[2].count;
As your json object does not have any key named as values.
What you have to do is first access the counts key then get the particular object from it which contains the particular(current date as in your case) and then get the counts from it.
Below is a sample code to get the particular date's count:
//assuming this is the Json response you are getting as complete JSON response is not provided by the OP.
var getcounts = `[{"type":{"id":"mobile","name":"mobile","description":"","total_count":0},"counts":[{"date":"2018-09-05","timestamp":1533686400000,"count":0},{"date":"2018-09-06","timestamp":1533772800000,"count":8}]}]`;
//parsing the given json String
var json_count = JSON.parse(getcounts);
function getCountForCurrentDate() {
var curDate = getCurrentDate(); //for which the data is to be fetched and making in format of the dates in JSON as yyyy-mm-dd
//finding the particular object that contains the current date
var searchedObj = json_count[0]['counts'].find(f => f['date'] == curDate);
if(searchedObj!==undefined)
console.log('count is', searchedObj['count']);
}
function getCurrentDate() {
var nowDate = new Date();
var month = (nowDate.getMonth() + 1).toString().length == 1 ? '0' + (nowDate.getMonth() + 1) : (nowDate.getMonth() + 1);
var day = nowDate.getDate().toString().length == 1 ? '0' + nowDate.getDate() : +nowDate.getDate();
return nowDate.getFullYear() + '-' + month + '-' + day;
}
getCountForCurrentDate();
Here in the snippet above, i have created two functions getCurrentDate() to get the current date in the format it is stored in JSON response and getCountForCurrentDate() to get the count from the json_count variable.
Update 1 as per the new requirement is given by OP
The given JSON object is as follows:
var json_count = [
{
type: {
id: "mobile",
name: "mobile",
description: "",
total_count: 0
},
counts: [
{
date: "2018-09-06",
timestamp: 1536192000000,
count: 20
},
{
date: "2018-09-07",
timestamp: 1536278400000,
count: 10
}
]
},
{
type: {
id: "lap",
name: "lap",
description: "",
total_count: 0
},
counts: [
{
date: "2018-09-06",
timestamp: 1536192000000,
count: 19
},
{
date: "2018-09-07",
timestamp: 1536278400000,
count: 20
}
]
}
];
And now as the object has two entities one for mobile and another for lap we can fetch the particular values as:
var mobile = json_count.find(f=>f['type']['id']=='mobile');//comparing the value present in the json object at location type.id to 'mobile' (change it to 'lap' or anything that is present in the id of the object).
and now to get the count for it we do as:
var mobile_count = mobile.counts.find(f=>f['date']=='2018-09-07');//replace the static date with the date you want to fetch the count from
and then access the count as:
console.log(mobile_count.count);
//output:10
Related
I am getting below response from api .
Below is sample respone not real
Each object has createdDate , I have to group value is weekwise wise like.
like 2022-10-01 and 2022-10-02 both are 1st week of Oct , and 2022-10-10 3rd Week of Oct
{
"data": {
"fetchOrdersAndRequest": [
{
"id": "PI786971",
"customerId": [
"C200147"
],
"createdDate": "2022-10-01T04:46:00.126Z",
}
{
"id": "PI786972",
"customerId": [
"C200148"
],
"createdDate": "2022-10-02T04:46:00.126Z",
}
{
"id": "PI786972",
"customerId": [
"C200149"
],
"createdDate": "2022-10-10T04:46:00.126Z",
}
{
"id": "PI786969",
"customerId": [
"C200146"
],
"createdDate": "2022-10-24T04:46:00.126Z",
}
{
"id": "PI786968",
"customerId": [
"C200145"
],
"createdDate": "2022-10-29T04:46:00.126Z",
}
]
}
}
I have to convert the response like below , monthly value I have to convert weekly
{
period:'lastMonth',
Week:[
{
"key":"Week1",
"value" : [{
"id": "PI786971",
"customerId": [
"C200147"
],
"createdDate": "2022-10-01T04:46:00.126Z",
}
{
"id": "PI786972",
"customerId": [
"C200148"
],
"createdDate": "2022-10-02T04:46:00.126Z",
}],
"date": [{2022-10-01}{2022-10-02}]
},
{
"key":"Week2",
"value" : [],
"date:[]
},
{
"key":"Week3",
"value" : [{
"id": "PI786972",
"customerId": [
"C200149"
],
"createdDate": "2022-10-10T04:46:00.126Z",
}],
"date":[{2022-10-10}]
},
{
"key":"Week4",
"value" : [{}],
},
{
"key":"week5",
"value" : []
"date":[{2022-10-24}{2022-10-29}]
},
{
"key":"Week6",
"value" : [],
"date:[]
},
]
// Using below code I am able to filter weeks and my weeks startng from sunday to Saturday , but now I have to puch my api response data matching to dates
fetchMonthWeek = ()=>{
var today = new Date();
const month = today.getMonth() + 1
const year = today.getFullYear()
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let weeks = {}
var totalDays = new Date(year, month, 0).getDate();
let weekCount = 1
for (let i = 1; i <= totalDays; i++) {
const date = (i < 10 ? '0' + i : i)
const fullDate = (year + '-' + (month < 10 ? '0' + month : month) + '-' + date)
const currentDay = days[new Date(fullDate).getDay()]
if (currentDay === days[0]) weekCount++
const w = 'Week' + weekCount
if (weeks[w]) {
weeks[w].push(fullDate)
} else weeks[w] = [fullDate]
}
console.log(weeks)
let newData = []
for (const w in weeks) {
newData.push({
key: w,
range: {
startDate: weeks[w][0],
endDate: weeks[w][weeks[w].length - 1]
},
value: weeks[w]
})
}
return newData
}
Please help .
Thank you
I want to create a file tree format in JSON based on other JSON. The idea is to reorganize the JSON data in a tree format.
Note that the name of the file indicates where it is located in the tree.
Let's suppose that we have this first JSON:
{
"dir1/file3.xyz":
[
18KB,
"2020-01-01 00:00:00"
],
"dir1/file4.xyz":
[
18KB,
"2020-01-02 00:00:00"
],
"dir1/subdir1/file5.xyz":
[
18KB,
"2020-01-01 00:00:00"
],
"dir1/subdir1/file6.xyz":
[
18KB,
"2020-01-02 00:00:00"
],
"file1.xyz":
[
18KB,
"2020-01-01 00:00:00"
],
"file2.xyz":
[
18KB,
"2020-01-02 00:00:00"
]
}
I want to create a JSON based on the previous one in this format:
[
directories: [
{
name: 'dir1',
directories: [
{
name: 'subdir1',
directories: [],
files: [
{
name: 'file5.xyz',
size: '19KB',
modified: '2020-01-01 00:00:00'
},
{
name: 'file6.xyz',
size: '20KB',
modified: '2020-01-02 00:00:00'
}
]
}
],
files: [
{
name: 'file3.xyz',
size: '19KB',
modified: '2020-01-01 00:00:00'
},
{
name: 'file4.xyz',
size: '20KB',
modified: '2020-01-02 00:00:00'
}
]
}
],
files: [
{
name: 'file1.xyz',
size: '19KB',
modified: '2020-01-01 00:00:00'
},
{
name: 'file2.xyz',
size: '20KB',
modified: '2020-01-02 00:00:00'
}
]
Thank you for your time.
We solved this challenge using the JavaScript code logic below:
function fillWithZero(intValue){
return intValue > 9 ? intValue : '0' + intValue;
}
function list_to_tree(list) {
var map = {}, i;
var root = {};
root.text = '/';
root.value = '';
root.disabled = true;
root.children = [];
map['/'] = root;
for (i = 0; i < list.length; i += 1) {
node = list[i];
var current = {};
var d = node.date;
var datestring = fillWithZero(d.getDate()) + "-" + fillWithZero(d.getMonth()+1) + "-" + d.getFullYear() + " " + fillWithZero(d.getHours()) + ":" + fillWithZero(d.getMinutes()) + ":" + fillWithZero(d.getSeconds());
current.text = node.name + ' - Size: ' + parseInt(node.size/1024) + 'KB' + ' Modified: ' + datestring;
current.value = node.name;
var parent = root;
if (node.name.indexOf('/') > 0) {
var paths = node.name.split('/');
for (j = 0; j < paths.length - 1; j += 1) {
var dirId = paths[j];
var dir = map[dirId];
if (dir == null) {
dir = {};
dir.text = dirId;
dir.value = dirId;
if(parent != root){
dir.value = parent.value + '/' + dirId;
}
dir.disabled = true;
dir.children = [];
map[dirId] = dir;
parent.children.push(dir);
}
parent = dir;
}
current.text = node.name.substr(node.name.lastIndexOf('/') + 1, node.name.length) + ' - Size: ' + parseInt(node.size/1024) + 'KB' + ' Modified: ' + datestring;
}
parent.children.push(current);
}
return root;
}
var entries = [{
"name": "dir1/file1.xyz",
"size": 4234,
"date": new Date()
}, {
"name": "dir1/file2.xyz",
"size": 4234,
"date": new Date()
}, {
"name": "dir1/subdir1/file3.xyz",
"size": 4234,
"date": new Date()
}, {
"name": "dir1/subdir1/file4.xyz",
"size": 4234,
"date": new Date()
}, {
"name": "file3.xyz",
"size": 4234,
"date": new Date()
}, {
"name": "file4.xyz",
"size": 4234,
"date": new Date()
}
];
console.log(list_to_tree(entries));
So, the this is about consuming an API that has a date/time property. The content should change every 3 hours by comparing current user Date/time with that of the API and also assigning past and upcoming hours in a separate an arrays to be displayed in other section of the page. I managed to assign past and upcoming dates to their respective arrays. I need to compare the date and to assign "current data" if the user Date/Time is equal to or within 3 hours in a property to display it for the whole duration of three hours.
this.dataService.getData().subscribe((data:any[])=>{
const now = new Date('2021-02-14 09:00:00');
for (const item of data) {
const apiDate = new Date(item.dateTime);
if(now.getTime() > apiDate.getTime()){
this.future.push('future dates')
} else if(now.getTime() < apiDate.getTime()){
this.past.push('past dates')
}else if(now.getTime() == apiDate.getTime()){
//in real time, they'll only be equal for one second
this.current = 'Show NOW'
}
}
This is the structure of API/Json Data retuned
[ { "number": 10, "dateTime": "2021-02-14 00:00:00" }, { "number": 20, "dateTime": "2021-02-14 03:00:00" }, { "number": 30, "dateTime": "2021-02-14 06:00:00" }, { "number": 40, "dateTime": "2021-02-14 09:00:00" }, { "number": 50, "dateTime": "2021-02-14 12:00:00" }]
a better approach to this would even be better.
Thanks
If your want to show time within range, then you can create an object with your time boundaries:
getTimeInterval = () => {
const from = new Date();
const to = new Date(from);
to.setHours(to.getHours() + 3)
return { from, to };
}
and then just check both boundaries of date from and to:
this.dataService.getData().subscribe((data:any[])=>{
const dateRange = this.getTimeInterval();
for (const item of data) {
const apiDate = new Date(item.dateTime);
if (dateRange.from.getTime() > apiDate.getTime()
&& dateRange.to.getTime() > apiDate.getTime())
{
this.future.push('future dates');
}
else if(dateRange.from.getTime() < apiDate.getTime())
{
this.past.push('past dates')
}
else if (dateRange.from.getTime() >= apiDate.getTime()
&& dateRange.to.getTime() <= apiDate.getTime())
{
this.current = 'Show NOW'
}
}
I have the following problem. I have an array of activities that I have to sort by date. The problem is that the "date" key is not always the same. If it's a one day activity it looks like:
date: "2019-10-25T00:00:00.000Z"
But if it's two days or longer, it looks like:
date:{dateFrom: "2017-05-13T00:00:00.000Z", dateTo: "2017-05-14T00:00:00.000Z"}
I've tried a normal sorting or the type of function that sort two keys that are never null.
So, how could I sort this array by date?
activities = [{
"date": {dateTo:"2019-05-20T00:00:00.000Z", dateFrom: "not important"},
activity: 5
},{
"date": {dateTo:"2019-05-05T00:00:00.000Z", dateFrom: "not important"},
activity: 2
},{
"date": "2019-05-10T00:00:00.000Z",
activity: 3
},{
"date": "2019-05-25T00:00:00.000Z",
activity: 6
},{
"date": "2019-05-01T00:00:00.000Z",
activity: 1
},{
"date": "2019-05-15T00:00:00.000Z",
activity: 4
}]
One solution would be to define a helper function like getItemDate(), combined with the regular Array#sort() method to achieve what you require:
const activities = [{
"date": {dateTo:"2019-05-20T00:00:00.000Z", dateFrom: "not important"},
activity: 5
},{
"date": {dateTo:"2019-05-05T00:00:00.000Z", dateFrom: "not important"},
activity: 2
},{
"date": "2019-05-10T00:00:00.000Z",
activity: 3
},{
"date": "2019-05-25T00:00:00.000Z",
activity: 6
},{
"date": "2019-05-01T00:00:00.000Z",
activity: 1
},{
"date": "2019-05-15T00:00:00.000Z",
activity: 4
}];
/* Define helper function that obtains a date timestamp from activities list item. If
date key is an object, item.date.dateTo is used, otherwise item.date is used */
function getItemDate(item) {
let date = (typeof item.date === 'object') ? item.date.dateTo : item.date;
return Date.parse(date);
}
/* Use helper function to sort items in activities list */
activities.sort((a,b) => getItemDate(a) - getItemDate(b))
console.log(activities)
You can use the sort-method of arrays and do a custom comparison. Inside the compare-function you can get the date-string from the two objects and convert it to a timestamp with the help of Date.parse. After that you have to compare these timestamps and return the sorting-rule (-1, 1 or 0).
let activities = [{
"date": {dateTo:"2019-05-20T00:00:00.000Z", dateFrom: "not important"},
activity: 5
},{
"date": {dateTo:"2019-05-05T00:00:00.000Z", dateFrom: "not important"},
activity: 2
},{
"date": "2019-05-10T00:00:00.000Z",
activity: 3
},{
"date": "2019-05-25T00:00:00.000Z",
activity: 6
},{
"date": "2019-05-01T00:00:00.000Z",
activity: 1
},{
"date": "2019-05-15T00:00:00.000Z",
activity: 4
}];
function compare( a, b ) {
let aDateString = a.date.dateTo ? a.date.dateTo : a.date;
let bDateString = b.date.dateTo ? b.date.dateTo : b.date;
let aDate = Date.parse(aDateString);
let bDate = Date.parse(bDateString);
if ( aDate < bDate ){
return -1;
}
if ( aDate > bDate ){
return 1;
}
return 0;
}
activities.sort( compare );
console.log(activities);
Check date property whether it has dateTo property or not and sort it with its value.
const activities = [{
"date": {
dateTo: "2019-05-20T00:00:00.000Z",
dateFrom: "not important"
},
activity: 5
}, {
"date": {
dateTo: "2019-05-05T00:00:00.000Z",
dateFrom: "not important"
},
activity: 2
}, {
"date": "2019-05-10T00:00:00.000Z",
activity: 3
}, {
"date": "2019-05-25T00:00:00.000Z",
activity: 6
}, {
"date": "2019-05-01T00:00:00.000Z",
activity: 1
}, {
"date": "2019-05-15T00:00:00.000Z",
activity: 4
}]
activities.sort((a, b) => {
const x = a.date.dateTo || a.date
const y = b.date.dateTo || b.date
if (x > y) return 1
if (x < y) return -1
return 0
})
console.log(activities)
const newActivities = activities.map((act) => {
const { activity, date } = act;
if(typeof date === 'string'){
return { date: Date.parse(date), activity }
}
return { date: Date.parse(date.dateTo), activity}
})
newActivties.sort((a,b) => a - b)
I have the following array and three vars:
array1 = ['']
dateOutput = 1/1/14
timeOutput = 12am
tallysave = 100
I was using this to push in the three vars on a push
array1.push(dateOutput + ', ' + timeOutput + tallysave)
However how can I push each of the vars into the array so they will be like this when pushed: (multi-dimensional array?)
array = [
{ "date": dateOutput, "time": timeOutput, },
];
You can push the data as an object:
array1.push({
"date": dateOutput,
"time": timeOutput
});
array1.push({ "date": dateOutput, "time": timeOutput})
or
array1.push([dateOutput, timeOutput])
But in the second way you should know that dateOutput with index 0, and timeOutput with index 1