I am reading data from a json file and storing it in an object in javascript , I am using d3js library to read the file.
This is what the raw data looks like in data.json file :
{
"bitcoin": [
{
"24h_vol": null,
"date": "12/5/2013",
"market_cap": null,
"price_usd": null
},
{
"24h_vol": null,
"date": "13/5/2013",
"market_cap": null,
"price_usd": null
},
{
"24h_vol": "0",
"date": "14/5/2013",
"market_cap": "1500517590",
"price_usd": "135.3"
},...]
"bitcoin_cash": [
{
"24h_vol": null,
"date": "12/5/2013",
"market_cap": null,
"price_usd": null
},
{
"24h_vol": null,
"date": "13/5/2013",
"market_cap": null,
"price_usd": null
},...]
}
I read this and then filter some of the null entries out and also parse the date and Integer values respectively, This is the code for the same:
//Get data
d3.json("data/coins.json").then((data) => {
console.log("original data", data.bitcoin);
/*---
original data (1633) [{…}, , …]
[0 … 99]
0: {24h_vol: null, date: "12/5/2013", market_cap: null, price_usd: null}
1: {24h_vol: null, date: "13/5/2013", market_cap: null, price_usd: null}
2: {24h_vol: "0", date: Tue May 14 2013 00:00:00 GMT-0400 (Eastern Daylight Time), market_cap: 1500517590, price_usd: 135.3}
...
--------*/
//Selector listener
$("#coin-select").change(function() {
var coinType =this.value;
var coinData = data[coinType];
var cleanData = coinData.filter((d) => {
return (d.price_usd)
}).map((d) => {
d.price_usd =+ d.price_usd;
d.market_cap =+ d.market_cap;
d.date = parsedDate(d.date);
return d;
});
console.log("cleanData", cleanData)
/*------
cleanData (1631) [{…}, {…}, , …]
[0 … 99]
0: {24h_vol: "0", date: Tue May 14 2013 00:00:00 GMT-0400 (Eastern Daylight Time), market_cap: 1500517590, price_usd: 135.3}
1: {24h_vol: "0", date: Wed May 15 2013 00:00:00 GMT-0400 (Eastern Daylight Time), market_cap: 1575032004, price_usd: 141.96}
---*/
update(cleanData);
});
//Default to bitcoin
$('#coin-select')
.val('bitcoin')
.trigger('change');
});
As you can see the console output , the original data has parsed values for date,market_cap and price_usd too, not sure why this is happening.
Thanks for you time.
PS: this doesn't only happens in chrome as suggested in the question : Is Chrome's JavaScript console lazy about evaluating arrays?
Try something like this:
$("#coin-select").change(function() {
var coinType = this.value;
var coinData = data[coinType];
var cleanData = coinData.filter(x => x.price_usd)
.map(d => ({
price_usd: d.price_usd =+ d.price_usd,
market_cap: d.market_cap =+ d.market_cap,
date: parsedDate(d.date)
}));
update(cleanData);
});
This makes sure you return a new object from your map so you do not mutate the original and also cleans up some of the explicit returns you had which are not needed.
Related
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.
I am trying to parse JSON but it keeps returning
Uncaught SyntaxError: Unexpected token & in JSON at position 1
at JSON.parse (<anonymous>)
The code looks like this in VS Code:
var result = '{{ bans }}';
var res = JSON.parse(result)
But in the consol it looks like:
var result = '{'bans': [{'appealable': False, 'banend': 'Fri, 15 Jan 2021 00:00:00 GMT', 'bannedby': 'parker02311', 'banstart': 'Fri, 15 Jan 2021 00:18:58 GMT', 'id': 1, 'images': 'https://cdn.discordapp.com/attachments/642127559600898058/799867505727504464/Roblox_1_15_2021_11_07_09_PM_2.png,https://cdn.discordapp.com/attachments/642127559600898058/799863972915314688/Roblox_1_15_2021_10_53_30_PM_2.png', 'notes': '<p>test</p>', 'reasons': 'Chat Bypassing, Discrimination', 'userid': '17', 'username': 'test'}, {'appealable': False, 'banend': 'Wed, 20 Jan 2021 00:00:00 GMT', 'bannedby': 'parker02311', 'banstart': 'Sat, 16 Jan 2021 05:46:33 GMT', 'id': 2, 'images': 'https://image.prntscr.com/image/DUQMlOEKTuGDHSkvB4NuRQ.png,https://cdn.discordapp.com/attachments/642127559600898058/799874004457488394/unknown.png', 'notes': '', 'reasons': 'Chat Bypassing,Discrimination', 'userid': '202181894', 'username': 'Dagdoubleagaming'}]}';
var res = JSON.parse(result)
I am not sure where all the ''s came from because the backend looks like:
r = requests.get('http://localhost:5001/get/bans', timeout=5)
if r.status_code == 200:
jsonre = r.json()
return render_template('index.html', name=current_user.username, title='Dashboard', breadcrums=True, bans=jsonre)
The request returns:
{
"bans": [
{
"appealable": false,
"banend": "Fri, 15 Jan 2021 00:00:00 GMT",
"bannedby": "parker02311",
"banstart": "Fri, 15 Jan 2021 00:18:58 GMT",
"id": 1,
"images": "https://cdn.discordapp.com/attachments/642127559600898058/799867505727504464/Roblox_1_15_2021_11_07_09_PM_2.png,https://cdn.discordapp.com/attachments/642127559600898058/799863972915314688/Roblox_1_15_2021_10_53_30_PM_2.png",
"notes": "<p>test</p>",
"reasons": "Chat Bypassing, Discrimination",
"userid": "17",
"username": "test"
},
{
"appealable": false,
"banend": "Wed, 20 Jan 2021 00:00:00 GMT",
"bannedby": "parker02311",
"banstart": "Sat, 16 Jan 2021 05:46:33 GMT",
"id": 2,
"images": "https://image.prntscr.com/image/DUQMlOEKTuGDHSkvB4NuRQ.png,https://cdn.discordapp.com/attachments/642127559600898058/799874004457488394/unknown.png",
"notes": "",
"reasons": "Chat Bypassing,Discrimination",
"userid": "202181894",
"username": "Dagdoubleagaming"
}
]
}
var result = '{{ bans | escapejs }}'
Just taking a shot here, but I took a look here "https://www.w3schools.com/Js/js_json_parse.asp" and I think this might work. I don't think the string is in json format that's why you're getting the error.
var result = '{"bans"}';
var res = JSON.parse(result)
I'm using the DHTMLX Scheduler in my web app and want to get the data for each event and found a way to do it with scheduler._events which returns this:
1581498064943: {…}
_eday: 2
_end_date: undefined
_first_chunk: true
_last_chunk: true
_length: 1
_sday: 1
_sorder: 0
_sweek: 0
_timed: true
end_date: Date Tue Jan 02 2018 00:05:00 GMT+0100 (Central European Standard Time)
event_length: ""
event_pid: ""
id: 1581498064943
rec_pattern: ""
rec_type: ""
start_date: Date Tue Jan 02 2018 00:00:00 GMT+0100 (Central European Standard Time)
text: "New event"
the problem is when I convert it into a string to store it as a JSON later, JavaScript converts dates into iso 8601 and loses a day in the conversion:
"1581498064943": {
"start_date": "2018-01-01T23:00:00.000Z",
"end_date": "2018-01-01T23:05:00.000Z",
"text": "New event",
"id": 1581498064943,
"_timed": true,
"_sday": 1,
"_eday": 2,
"_length": 1,
"_sweek": 0,
"_sorder": 0,
"_first_chunk": true,
"_last_chunk": true,
"event_pid": "",
"event_length": "",
"rec_pattern": "",
"rec_type": ""
2018-01-02 becomes 2018-01-01
It's not reducing oneday. It's because of your timeZone.
check the following code.
var x= new Date("Date Tue Jan 02 2018 00:05:00 GMT+0100 (Central European Standard Time)")
x.toISOString()
y = new Date(x)
You will get the initial date again. So, to use it from the JSON again you need that ISOstring to be converted again
Better try with Unix epoch seconds format to resolve this issue.
const now = Date.now(); // Unix timestamp in milliseconds
console.log( now );
Once you convert this you can retrieve the same exact time based on your local region specification.
var utcSeconds = 1581501372817/1000;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
console.log(d);
I have to do something like left join in sql in node with JSON data. Actually, on componentWillReceiveProps react (if it's changing anything).
my state:
const dayList = {
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": [],
"2017-11-11": [],
"2017-11-12": [],
"2017-11-13": []
}
my data to join:
const visit = {
"2017-11-11": "10:30",
"2017-11-12": "10:00",
"2017-11-12": "10:30"
}
And in componentdidmount i need to setState so that as result get that:
const dayList = {
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": [],
"2017-11-11": ["10:30"],
"2017-11-12": ["10:00","10:30"],
"2017-11-13": []
}
I know how to achieve it with .map, and another loop inside with if statement. But I am sure that there is a better approach.
What may you suggest?
Yes, actually you are right. I answered the wrong question. Is not a valid JSON neither.
But still, there is a case to do.
My very raw data from db looks like that:
[
{
"createDate": "Tue Nov 07 2017 20:56:27 GMT+0100",
"visitDate": "20171110",
"visitTime": "1030",
"doctor": {
"name": "name1"
}
},
{
"createDate": "Tue Nov 07 2017 20:56:36 GMT+0100",
"visitDate": "20171111",
"visitTime": "1000",
"doctor": {
"name": "name1"
}
},
{
"createDate": "Tue Nov 07 2017 23:30:03 GMT+0100",
"visitDate": "20171111",
"visitTime": "1030",
"doctor": {
"name": "name1"
}
}
];
and in react component and need to display it as a list of visits per day like that
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": ["10:30"],
"2017-11-11": ["10:00","10:30"],
"2017-11-12": []
"2017-11-13": []
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')