I have JSON data in this format:
{
"status":"Good",
"open_slots":[
{
"date":"Tue, Jun 28, 2016",
"time_slot":"9:15 AM"
},
{
"date":"Tue, Jun 28, 2016",
"time_slot":"12:30 PM"
},
{
"date":"Tue, Jun 28, 2016",
"time_slot":"2:00 PM"
}
]
}
How can I ignore the 'status' portion of the data and build a list based on open_slots with jQuery?
var json = JSON.parse(input);
var json_keep = json.open_slots;
Now you can loop over just the open slots:
for (var i = 0; i < json_keep.length; i++) {
alert("Found date/time_slot: " + json_keep[i].date + "/" + json_keep[i].time_slot);
}
Related
so I am using the momentJS library as the moment to create an array of 7 days in a week like this:
const moment = require('moment')
var startOfWeek = moment().startOf('week');
var endOfWeek = moment().endOf('week');
var days = [];
var day = startOfWeek;
while (day <= endOfWeek) {
days.push(day.format("MMMM ddd DD, YYYY "));
day = day.clone().add(1, 'd');
}
console.log(days);
And the result return an array of 7 days a week like this:
["December Sun 25, 2022 ","December Mon 26, 2022 ", "December Tue 27, 2022 " , "December Wed 28, 2022 ", "December Thu 29, 2022 ", "December Fri 30, 2022 ", "December Sat 31, 2022 "]
But the result that I look for is something like this:
const weekday = [
{
day: Mon,
date: 26
},
{
day: Tue,
date: 27
},
{
day: Wed,
date: 28
},
{
day: Thu,
date: 26
},
{
day: Fri,
date: 26
},
{
day: Sat,
date: 26
},
]
I am stuck on how to convert the data, could anyone able to help me ? Thanks
Without momentjs, you can use toLocaleDateString and other native Date methods to achieve the result:
const day = new Date(); // Today
day.setDate(day.getDate() - day.getDay() - 1); // Most recent Saturday (not today)
const weekday = Array.from({length: 7}, () => (
day.setDate(day.getDate() + 1), {
day: day.toLocaleDateString("en-US", { weekday: "short" }),
date: day.getDate(),
}
));
console.log(weekday);
If you wish to keep the original output to use elsewhere and not modify the original code, you can map over the days array and construct a new array based on the formatted string (converting to an integer as necessary).
const days = ["December Sun 25, 2022 ", "December Mon 26, 2022 ", "December Tue 27, 2022 ", "December Wed 28, 2022 ", "December Thu 29, 2022 ", "December Fri 30, 2022 ", "December Sat 31, 2022 "]
const weekday = days.map((formattedDate) => {
const [_, day, dateString] = formattedDate.split(" ");
return {
day,
date: parseInt(dateString)
};
});
console.log(weekday);
Alternatively, you can modify your original code
//const moment = require('moment')
const startOfWeek = moment().startOf('week');
const endOfWeek = moment().endOf('week');
// uncomment if you still want `days`
// const days = [];
const weekday = [];
let day = startOfWeek;
while (day <= endOfWeek) {
// days.push(day.format("MMMM ddd DD, YYYY "));
weekday.push({ day: day.format("ddd"), date: day.date() });
day = day.clone().add(1, 'd');
}
console.log(weekday);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
I had posted this question earlier but someone deleted with How can I access and process nested objects, arrays or JSON?
as possible answer. This is not helping me since a) The key 'date' is spread across several names, b)The objects comprises on arrays & objects & c) The depth at which the key 'date' is present can change.
Hence posting the question again.
I have a JS object as below
const bb = {
Harry: {
details: [
{
cat: "Life",
values: [
{
date: "2021-08-02",
level: 77.6,
},
{
date: "2021-08-03",
level: 79.1,
},
],
},
],
},
Barry: {
details: [
{
cat: "Logic",
values: [
{
date: "2021-08-02",
level: 77.6,
},
{
date: "2021-08-03",
level: 79.1,
},
],
},
],
},
};
I also have a variable defined for parsing the dates const dateParse = d3.timeParse("%Y-%m-%d")
I want to parse all the dates in the object. Since the 'date' is few levels below in the object, I am not able to figure this out. How do I go about it?
The expected output is
const bb = {
Harry: {
details: [
{
cat: "Life",
values: [
{
date: Mon Aug 02 2021 00:00:00 GMT+0530 (India Standard Time),
level: 77.6,
},
{
date: Tue Aug 03 2021 00:00:00 GMT+0530 (India Standard Time),
level: 79.1,
},
],
},
],
},
Barry: {
details: [
{
cat: "Logic",
values: [
{
date: Mon Aug 02 2021 00:00:00 GMT+0530 (India Standard Time),
level: 77.6,
},
{
date: Tue Aug 03 2021 00:00:00 GMT+0530 (India Standard Time),
level: 79.1,
},
],
},
],
},
};
You just have to loop through the objects, select the date node and execute
(new Date(datestring)).toString()
This will generate the date as specified in your output.
const bb = { Harry: { details: [{cat: "Life",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]},Barry: {details: [{cat: "Logic",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]}};
Object.values(bb).forEach((value) => {
value.details.forEach((detail) => {
detail.values.forEach((value) => {
value.date = (new Date(value.date)).toString();
})
})
});
console.log(bb);
If you want to parse all the nested date keys, you can do it recursively using the below functions
const bb = { Harry: { details: [{cat: "Life",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]},Barry: {details: [{cat: "Logic",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]}};
function traverseArray(inputArray) {
for (const arrayValue of inputArray) {
traverseObject(arrayValue);
}
}
function traverseObject(inputObject) {
for (const key in inputObject) {
const value = inputObject[key];
const valueType = typeof(value);
if (valueType == "object") {
traverseObject(value);
} else if (valueType == "array") {
traverseArray(value);
} else if (key == "date") { // since I want to parse only date keys
inputObject[key] = 'd3.timeParse("%Y-%m-%d") - Parse date here';
}
}
}
traverseObject(bb);
console.log(bb);
Unfortunately I have again problems with my grouped messages. I have already received a lot of help from you, so I feel a bit embarrassed to ask again - but I'm not getting ahead with this.
My first goal was to group messages by their created_date. Thanks to your help this works very well now. Now I have tried to output the grouped messages, but it does not work. I slowly don't understand the whole thing anymore...
I want to output the group key (date) first and then every single message in each group. This is what I’ve tried:
jQuery(document).ready(function ($) {
let messages = [{
sender_id: "0",
message: "Test",
created_at: "Thu Mar 12 2020 17:26:23 GMT+0100 (Mitteleuropäische Normalzeit)"
}, {
sender_id: "0",
message: "Hallo",
created_at: "Thu Mar 12 2020 17:26:23 GMT+0100 (Mitteleuropäische Normalzeit)"
}];
let groupedMessages = [];
$(messages).each(function (index, message) {
let createdAtDate = new Date(message["created_at"]).toLocaleDateString(navigator.language, {
day: "2-digit",
month: "2-digit",
year: "numeric"
});
if (typeof groupedMessages[createdAtDate] === "undefined") {
groupedMessages[createdAtDate] = [];
}
groupedMessages[createdAtDate].push(message);
});
console.log(groupedMessages);
if (groupedMessages && groupedMessages.length > 0) {
$(groupedMessages).each(function (index, messages) {
console.log(index); //Expected output: 12.03.2020
$(messages).each(function (index, message) {
console.log(message["sender_id"]);
console.log(message["message"]);
console.log(message["created_at"]);
})
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The issue is because of this line
let groupedMessages = []
You are setting groupedMessages as an array when it should be an object. array's don't have keys in JavaScript, which is why you get no output.
jQuery(document).ready(function ($) {
let messages = [{
sender_id: "0",
message: "Test",
created_at: "Thu Mar 12 2020 17:26:23 GMT+0100 (Mitteleuropäische Normalzeit)"
}, {
sender_id: "0",
message: "Hallo",
created_at: "Thu Mar 12 2020 17:26:23 GMT+0100 (Mitteleuropäische Normalzeit)"
}];
let groupedMessages = {};
$(messages).each(function (index, message) {
let createdAtDate = new Date(message["created_at"]).toLocaleDateString(navigator.language, {
day: "2-digit",
month: "2-digit",
year: "numeric"
});
if (typeof groupedMessages[createdAtDate] === "undefined") {
groupedMessages[createdAtDate] = [];
}
groupedMessages[createdAtDate].push(message);
});
console.log(groupedMessages);
if (groupedMessages && groupedMessages.length > 0) {
$(groupedMessages).each(function (index, messages) {
console.log(index); //Expected output: 12.03.2020
$(messages).each(function (index, message) {
console.log(message["sender_id"]);
console.log(message["message"]);
console.log(message["created_at"]);
})
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
To solve your problem I would suggest you such things:
You can`t use string keys for arrays, use objects in case you want to have string keys
Do not use $().each... because it iterates over jQuery collections, instead use built in js functions of $.each to iterate over js object or array.
Check solution below
jQuery(document).ready(function ($) {
let messages = [{
sender_id: "0",
message: "Test",
created_at: "Thu Mar 12 2020 17:26:23 GMT+0100 (Mitteleuropäische Normalzeit)"
}, {
sender_id: "0",
message: "Hallo",
created_at: "Thu Mar 12 2020 17:26:23 GMT+0100 (Mitteleuropäische Normalzeit)"
}];
let groupedMessages = {};
messages.forEach(function (message, index) {
let createdAtDate = new Date(message["created_at"]).toLocaleDateString(navigator.language, {
day: "2-digit",
month: "2-digit",
year: "numeric"
});
if (typeof groupedMessages[createdAtDate] === "undefined") {
groupedMessages[createdAtDate] = [];
}
groupedMessages[createdAtDate].push(message);
});
console.log(groupedMessages);
if (Object.keys(groupedMessages).length)
{
Object.keys(groupedMessages).map(date => {
console.log(date); //Expected output: 12.03.2020
groupedMessages[date].map(message => {
console.log(message["sender_id"]);
console.log(message["message"]);
console.log(message["created_at"]);
})
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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);
I have the below nodejs code that reads contents of baseline.json file and parse it. I then try to display all the Computer ID and LastReportTime. I see an odd behaviour it would not print all the ID and LastReportTime. Also, the results are different every time i run it. The json is big for me to upload here so i uploaded on Json Blob.
Nodejs Code
var fs = require('fs');
try {
var json = JSON.parse(fs.readFileSync('baseline.json'));
for (var obj in json) {
if (json.hasOwnProperty(obj)) {
console.log(obj);
console.log("\n \n");
if (obj == "BESAPI") {
for (var prop in json[obj]) {
console.log(prop);
if (prop == "Computer") {
// loop over Computer dataseries
for (var id in json[obj][prop]) {
console.log(prop + ':' + json[obj][prop][id].ID);
console.log(prop + ':' + json[obj][prop][id].LastReportTime);
}
}
}
}
}
}
} catch (err) {
console.error(err);
}
Raw JSON
https://gist.github.com/anonymous/f27f75879e48c5387a03
In your posted array, LastReportTime and ID are arrays.
Try these lines:
console.log(prop + ':' + json[obj][prop][id].ID[0]);
console.log(prop + ':' + json[obj][prop][id].LastReportTime[0]);
If you pretty print you can see the data comes in two flavors, the top portion followed by the balance of the data in a standard form which does repeat 177 times
{
BESAPI: {
$: {
xmlns:xsi: "http://www.w3.org/2001/XMLSchema-instance",
xsi:noNamespaceSchemaLocation: "BESAPI.xsd"
},
Computer: [
{
$: {
Resource: "api/computer/2431038"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:54:41 +0000"
],
ID: [
"2431038"
]
},
{
$: {
Resource: "api/computer/16710075"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:45:18 +0000"
],
ID: [
"16710075"
]
},
{
$: {
Resource: "api/computer/3415985"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:50:52 +0000"
],
ID: [
"3415985"
]
},
{
$: {
Resource: "api/computer/11736335"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:54:41 +0000"
],
ID: [
"11736335"
]
},
I am chopping out many lines her, but it ends normally as
{
$: {
Resource: "api/computer/5520740"
},
LastReportTime: [
"Thu, 12 Feb 2015 02:49:11 +0000"
],
ID: [
"5520740"
]
}
]
}
}
Using nodejs you can pretty print using :
var pretty_print = require('js-object-pretty-print').pretty;
var parsed_data = JSON.parse(data_from_file);
console.log(pretty_print(parsed_data)); // good pretty print