dynamic key in mapping Object - javascript

hi i have an JSON object like this :
WorkTime=[{
"Day": "6",
"Time1": "8 : 00 - 9 : 00",
"Time2": "9 : 00 - 10 : 00",
"Time3": "10 : 00 - 11 : 00",
"Time4": "11 : 00 - 12 : 00",
"Time5": "12 : 00 - 13 : 00",
"Time6": "13 : 00 - 14 : 00",
"Time7": "17 : 00 - 18 : 00",
"Time8": "18 : 00 - 19 : 00",
"Time9": "19 : 00 - 20 : 00",
"id": 1
},
{
"Day": "0",
"Time1": "8 : 00 - 9 : 00",
"Time2": "9 : 00 - 10 : 00",
"Time3": "10 : 00 - 11 : 00",
"Time4": "11 : 00 - 12 : 00",
"Time5": "12 : 00 - 13 : 00",
"Time6": "13 : 00 - 14 : 00",
"id": 2
},]
and i want insert object's Value into My div . but i should write the Object key and my Number of Keys is Variable. for this i decide to use index and dynamic call Keys but i don't know anything about its Syntax .
What I want to do is almost like this :
{
WorkTime.map((item, index) => (
<div key={index} id={`Ticket${item.Day}Box`} className="bg-gray-50 p-3 w-11/12
rounded-t-xl mx-auto" style={{ display: "none" }}>
{item.Time{index+1}}
</div>
)) }
instead Of Call Keys Like This :
WorkTime.map((item, index) => (
<div key={index} id={`Ticket${item.Day}Box`} className="bg-gray-50 p-3 w-11/12
rounded-t-xl mx-auto" style={{ display: "none" }}>
{item.Time1}
</div>
)) }

To answer your question, you can use the brackets syntax and string interpolation to get what you want:
item[`Time${index + 1}`]
I'm assuming you do realize that this will only give you the first time entry from every WorkTime object. If you want to show all the time entries, you'll have to iterate over them separately. For this I'd recommend changing the structure of your json to something like this:
WorkTime = [{
id: 0, // whatever
day: "day string",
times: ["time 1", "time 2"] // etc
}]
It modifying json is not possible, then you can collect all the Time keys with this:
Object.keys(item).filter(k => k.match(/Time\d/))

Related

Amcharts: How to pass title in balloonFunction?

I want to format the data before passing it would be shown as a tooltip. For this purpose I use balloonFunction and compareGraphBalloonFunction
"stockGraphs": [
{
"id": "g1",
"valueField": "value",
"comparable": true,
"compareField": "value",
"balloonFunction": this.ballonRender,
"compareGraphBalloonFunction": this.ballonRender,
// This is works
//"balloonText": [[title]]
//"compareGraphBalloonText": [[title]]
}]
But when I send a title as a parameter to my ballonRender function I can't find the property that shows the name of my graph among title object.
ballonRender(title) {
let sign = (title["percents"]["value"]>0) ? "+" : "-";
let values = (title["values"]["value"]).toFixed(4)
let percentage = (title["percents"]["value"]).toFixed(2)
let newTitle = 'Product <b>%s</b> (%s %s%)'.format(values, sign, percentage)
return newTitle
},
If I print title inside my ballonRender function I observe the following object.
category : Mon Oct 02 2017 00:00:00 GMT+0800 (Гонконг, стандартное время) {}
dataContext : amCategoryIdField: "1506873600000"
dataContext : {__ob__: Observer}
date : Mon Oct 02 2017 08:00:00 GMT+0800 (Гонконг, стандартное время) {}
rawData : (5) [{…}, {…}, {…}, {…}, {…}]
valueAbsHigh : 1.0477245421
valueAverage : 1.04665801056
valueClose : 1.0466455011
valueCount : 5
valueHigh : 1.0477245421
valueLow : 1.0451341501
valueOpen : 1.0451341501
valueSum : 5.2332900528
graph : {id: "g1", valueField: "value", comparable: true, compareField: "value", balloonFunction: ƒ, …}
index : 40
isNegative : false
percents : {value: 4.664550109999993, percents: 23.826681846132807, total: 339.27455273}
serialDataItem : {dataContext: {…}, category: Mon Oct 02 2017 00:00:00 GMT+0800 (Гонконг, стандартное время), time: 1506873600000, axes: {…}, x: {…}}
values : {value: 1.0466455011, percents: 23.826681846132807, total: 4.3927455273}
x : 608
y : 359.7633884380001
I can't understand why [[title]] in balloonText works fine, but when I pass this parameter to the function I can't retrieve the graphs title.
Also I'm a bit confused about input parameters in ballonFunction in general. It wound be nice if you share a resource with explanation and best-practicies.
The title comes from the graph object itself. In the stock chart's case, the graph inherits the title from the dataSet, but the same property is populated. All you have to do is access the graph object that is passed as a second parameter to the balloonFunction, which you don't have in your function currently, to get the title data:
"balloonFunction": function(graphDataItem, graph) {
return "<u>" + graph.title + "</u>: <b>" + graphDataItem.values.value + "</b>";
},
"compareGraphBalloonFunction": function(graphDataItem, graph) {
return "<u>" + graph.title + "</u>: <b>" + graphDataItem.values.value + "</b>";
}
Demo

Convert buffered file data to Json object: express-fileupload

I am sending a JSON file over http. The file is available on req.files using the express-fileupload middleware. I am getting the file as a buffered data. I want to convert the file to a JSON object.
app.post('/start', function(req, res){
if(!req.files.seed)
res.status(400).send("Please upload the seed file");
var file = req.files.seed;
var obj = //Convert the file to JSON object and send it to create instance;
instance.createInstance(obj);
res.status(200).send("Started....");
});
When printed, the file looks like something this
{ name: 'seed.json',
data: <Buffer 7b 0d 0a 09 22 61 72 72 61 79 22 3a 20 5b 20 31 2c 20 31 20 5d 2 c 0d 0a 09 22 72 65 63 75 72 72 65 6e 63 65 22 3a 20 7b 0d 0a 09 09 22 73 65 63 6f 6e ... >,
encoding: '7bit',
mimetype: 'application/json',
mv: [Function: mv] }
I tried using JSON.parse(file) but SyntaxError: Unexpected token o in JSON at position 1 pops up.
I also tried using converting it to a string using
var text = file.toString(file,'utf8')
var obj = JSON.parse(text)
but this also doesn't seem to work. The properties of this objects, when accessed are undefined.
The JSON file structure.
{
"array": [ 1, 1 ],
"recurrence": {
"second": 50,
"minute": null,
"hour": null,
"dayOfweek": null
},
"campaign": {
"sender": "StartUp India Yatra",
"email": "fashion#getposhaq.com",
"subject": "{Invitation} StartUp India Yatra Chapter",
"title": "StartUp India Yatra Campaign"
},
"condition": {
"open": {
"greaterThanEqual": 1,
"lessThan": 2
},
"campaignSummary": null
},
"textPath": "../template.txt",
"htmlPath": "../template.html",
"path": "../emailer/index.js"
"retailerId": "4"
}
Given what you presented in the debug, your encoding is not utf8 but 7bit. So for a proper decoding you will need to change a bit your code.
var file = req.files.seed;
var obj = JSON.parse(file.data.toString('ascii'));
// ... do your creation logic
Any way you can play with the utf8, ascii econdings to see if you do not have JSON.parse problems.

How can I sort data on Mongodb

Here is data from MongoDB
{
"urls" : {
"beauty-credit" : {
"count" : 1,
"keyword" : "beauty credit",
"last_res" : 152,
"last_sea" : "Sat May 13 2017 15:16:41 GMT+0700 (SE Asia Standard Time)",
"url_site" : "beauty-credit"
},
"etude" : {
"count" : 2,
"keyword" : "etude",
"last_res" : 1048,
"last_sea" : "Sat May 13 2017 15:16:38 GMT+0700 (SE Asia Standard Time)",
"url_site" : "etude"
},
"skinfood" : {
"count" : 2,
"keyword" : "skinfood",
"last_res" : 478,
"last_sea" : "Sat May 13 2017 15:16:45 GMT+0700 (SE Asia Standard Time)",
"url_site" : "skinfood"
}
}
}
and Here is my code. Now I filter only last_res > 10
function gotData(data){
result = data.val()
const urls_kws = Object.keys(result)
.filter(key => result[key].last_res > 10)
}
How can I sort data by "count"? Also how can I show only 30 rows?
In order to sort the data by count you can use the sort() function from javascript with a custom comparator like
urls_kws.sort((a, b) => a.count - b.count)
In order to now get only the first 30 values, you can then slice the array
var short_urls_kws = urls_kws.slice(0, 30)

Parsing string to JSON using node gives unexpected token, validator says ok

I have the following string that I would like to parse to JSON :
{
"STATUS": [
{
"STATUS": "S",
"When": 1394044643,
"Code": 17,
"Msg": "GPU0",
"Description": "cgminer 3.7.3"
}
],
"GPU": [
{
"GPU": 0,
"Enabled": "Y",
"Status": "Alive",
"Temperature": 70,
"Fan Speed": 3089,
"Fan Percent": 70,
"GPU Clock": 1180,
"Memory Clock": 1500,
"GPU Voltage": 1.206,
"GPU Activity": 99,
"Powertune": 20,
"MHS av": 0.4999,
"MHS 5s": 0.5009,
"Accepted": 4335,
"Rejected": 7,
"Hardware Errors": 0,
"Utility": 27.8007,
"Intensity": "0",
"Last Share Pool": 0,
"Last Share Time": 1394044643,
"Total MH": 4676.7258,
"Diff1 Work": 69436,
"Difficulty Accepted": 69360,
"Difficulty Rejected": 112,
"Last Share Difficulty": 16,
"Last Valid Work": 1394044643,
"Device Hardware%": 0,
"Device Rejected%": 0.1613,
"Device Elapsed": 9356
}
],
"id": 1
}
When I use e.g. http://jsonlint.com/ it says that the JSON is correct but when I use in node.js:
console.log(JSON.parse(data.toString()));
I get the following :
undefined:1
e Hardware%":0.0000,"Device Rejected%":0.1570,"Device Elapsed":9554}],"id":1}
^
SyntaxError: Unexpected token
Any clue what am I doing wrong here ?
EDIT
The data is coming as ByteStream :
.on('data',function(data){
console.log(data.toString());
console.log();
console.log(data);
console.log();
console.log("data "+ data.GPU);
//...
//...
{"STATUS":[{"STATUS":"S","When":1394045650,"Code":17,"Msg":"GPU0","Description":"cgminer 3.7.3"}],"GPU":[{"GPU":0,"Enabled":"Y","Status":"Alive","Temperature":70.00,"Fan Speed":3090,"Fan Percent":70,"GPU Clock":1180,"Memory Clock":1500,"GPU Voltage":1.206,"GPU Activity":99,"Powertune":20,"MHS av":0.4999,"MHS 5s":0.5007,"Accepted":4841,"Rejected":8,"Hardware Errors":0,"Utility":28.0261,"Intensity":"0","Last Share Pool":0,"Last Share Time":1394045638,"Total MH":5181.3734,"Diff1 Work":77548,"Difficulty Accepted":77456.00000000,"Difficulty Rejected":128.00000000,"Last Share Difficulty":16.00000000,"Last Valid Work":1394045638,"Device Hardware%":0.0000,"Device Rejected%":0.1651,"Device Elapsed":10364}],"id":1}
<Buffer 7b 22 53 54 41 54 55 53 22 3a 5b 7b 22 53 54 41 54 55 53 22 3a 22 53 22 2c 22 57 68 65 6e 22 3a 31 33 39 34 30 34 35 32 34 38 2c 22 43 6f 64 65 22 3a 31 ...>
data undefined
EDIT
When I do this :
console.log(data.toString());
console.log(JSON.stringify(data.toString()));
I get the following result :
"{"STATUS":[{"STATUS":"S","When":1394046864,"Code":17,"Msg":"GPU0","Description":"cgminer 3.7.3"}],"GPU":[{"GPU":0,"Enabled":"Y","Status":"Alive","Temperature":70.00,"Fan Speed":3087,"Fan Percent":70,"GPU Clock":1180,"Memory Clock":1500,"GPU Voltage":1.206,"GPU Activity":99,"Powertune":20,"MHS av":0.5000,"MHS 5s":0.5016,"Accepted":5396,"Rejected":8,"Hardware Errors":0,"Utility":27.9597,"Intensity":"0","Last Share Pool":0,"Last Share Time":1394046864,"Total MH":5789.2352,"Diff1 Work":86428,"Difficulty Accepted":86336.00000000,"Difficulty Rejected":128.00000000,"Last Share Difficulty":16.00000000,"Last Valid Work
":1394046864,"Device Hardware%":0.0000,"Device Rejected%":0.1481,"Device Elapsed":11580}],"id":1}"
"{\"STATUS\":[{\"STATUS\":\"S\",\"When\":1394046864,\"Code\":17,\"Msg\":\"GPU0\",\"Description\":\"cgminer 3.7.3\"}],\"GPU\":[{\"GPU\":0,\"Enabled\":\"Y\",\"Status\":\"Alive\",\"Temperature\":70.00,\"Fan Sp
eed\":3087,\"Fan Percent\":70,\"GPU Clock\":1180,\"Memory Clock\":1500,\"GPU Voltage\":1.206,\"GPU Activity\":99,\"Powertune\":20,\"MHS av\":0.5000,\"MHS 5s\":0.5016,\"Accepted\":5396,\"Rejected\":8,\"Hardw
are Errors\":0,\"Utility\":27.9597,\"Intensity\":\"0\",\"Last Share Pool\":0,\"Last Share Time\":1394046864,\"Total MH\":5789.2352,\"Diff1 Work\":86428,\"Difficulty Accepted\":86336.00000000,\"Difficulty Re
jected\":128.00000000,\"Last Share Difficulty\":16.00000000,\"Last Valid Work\":1394046864,\"Device Hardware%\":0.0000,\"Device Rejected%\":0.1481,\"Device Elapsed\":11580}],\"id\":1}\u0000"
Notice the last unicode character of the second message \u0000 what can I do with it?
The problem was with the terminating null character. After removing it I can now parse the string no problemo ( post more efficient way if you have it)
var re = /\0/g;
str = data.toString().replace(re, "");
var o = JSON.parse(str);
console.log(o);
or
var str = data.toString().slice(0, - 1);
or work directly on bytes in Buffer
var buf = data.slice(0,data.length-1);
console.log(JSON.parse(buf.toString()));
I copied your console log output for data.toString() and and as #patryk pointed out, there is a unicode character \u0000 at the end of the string. That might be causing the problem. I removed the trailing character, assigned the string to a variable and created a buffer out of it and everything is hunky dory.
var a = '{"STATUS":[{"STATUS":"S","When":1394045650,"Code":17,"Msg":"GPU0","Description":"cgminer 3.7.3"}],"GPU":[{"GPU":0,"Enabled":"Y","Status":"Alive","Temperature":70.00,"Fan Speed":3090,"Fan Percent":70,"GPU Clock":1180,"Memory Clock":1500,"GPU Voltage":1.206,"GPU Activity":99,"Powertune":20,"MHS av":0.4999,"MHS 5s":0.5007,"Accepted":4841,"Rejected":8,"Hardware Errors":0,"Utility":28.0261,"Intensity":"0","Last Share Pool":0,"Last Share Time":1394045638,"Total MH":5181.3734,"Diff1 Work":77548,"Difficulty Accepted":77456.00000000,"Difficulty Rejected":128.00000000,"Last Share Difficulty":16.00000000,"Last Valid Work":1394045638,"Device Hardware%":0.0000,"Device Rejected%":0.1651,"Device Elapsed":10364}],"id":1}';
var b = new Buffer(a);
console.log(JSON.parse(b.toString());
output -
{ STATUS:
[ { STATUS: 'S',
When: 1394045650,
Code: 17,
Msg: 'GPU0',
Description: 'cgminer 3.7.3' } ],
GPU:
[ { GPU: 0,
Enabled: 'Y',
Status: 'Alive',
Temperature: 70,
'Fan Speed': 3090,
'Fan Percent': 70,
'GPU Clock': 1180,
'Memory Clock': 1500,
'GPU Voltage': 1.206,
'GPU Activity': 99,
Powertune: 20,
'MHS av': 0.4999,
'MHS 5s': 0.5007,
Accepted: 4841,
Rejected: 8,
'Hardware Errors': 0,
Utility: 28.0261,
Intensity: '0',
'Last Share Pool': 0,
'Last Share Time': 1394045638,
'Total MH': 5181.3734,
'Diff1 Work': 77548,
'Difficulty Accepted': 77456,
'Difficulty Rejected': 128,
'Last Share Difficulty': 16,
'Last Valid Work': 1394045638,
'Device Hardware%': 0,
'Device Rejected%': 0.1651,
'Device Elapsed': 10364 } ],
id: 1 }

How do I serialize this into JSON?

{
"_id" : ObjectId("4ccb42cb8aad692e01000004"),
"loc" : {
"lat" : 37.799506,
"long" : -122.459445
},
"test_set" : 1,
"title" : "Melissa Mills Housewife 01 SIGNED",
"num_comments" : 58,
"down_votes" : 66,
"up_votes" : 79,
"image_url" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg",
"image_url_thumb" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg",
"date" : "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)",
"flickr_id" : "5126544615"
}
One of the elements in thelist is above.
thejson = simplejson.dumps({"results":thelist})
However, I can't serialize this because of the date field. It can't serialize datetime.
I doubt that the problem has to do anything with datetime: in your dictionary, there is no datetime object at all, but the "date" key has a regular string value.
More likely, the problem is that it can't serialize the ObjectId class. To overcome this limitation, create a new class inheriting from JSONEncoder, and overriding the default method.
Unless i'm missing something - its the ObjectId that is causing the error (works for me here without it). You might want to consider munging or removing that field if not needed.
The date parses fine.
This works for me. I have removed ObjectId as I do not have the class with me.
result = {
"loc" : {
"lat" : 37.799506,
"long" : -122.459445
},
"test_set" : 1,
"title" : "Melissa Mills Housewife 01 SIGNED",
"num_comments" : 58,
"down_votes" : 66,
"up_votes" : 79,
"image_url" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg",
"image_url_thumb" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg",
"date" : "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)",
"flickr_id" : "5126544615"
}
import simplejson
thejson = simplejson.dumps(result)
print thejson
Output:
{"down_votes": 66, "loc": {"lat": 37.799506000000001, "long": -122.459445}, "image_url": "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg", "test_set": 1, "title": "Melissa Mills Housewife 01 SIGNED", "up_votes": 79, "num_comments": 58, "image_url_thumb": "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg", "date": "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)", "flickr_id": "5126544615"}
And if you are getting the following error, then you need to have class ObjectId :
"_id" : ObjectId("4ccb42cb8aad692e01000004"),
NameError: name 'ObjectId' is not defined

Categories

Resources