简体   繁体   中英

Converting JSON data into Chart.js array from strings

I'm pulling data from a JSON file stored as a Javascript variable:

 var jsonFile = { "profiles": [{ "time": 0, "conc": 0.15, "fitted": 0.1, "non": 0, "prior": 30, "missed": 2.9, "wrong": 2.9, "mix": 0.15, "temp": 0.015, "gel": 0.03, "data": 4 }, { "time": 1, "conc": 11, "fitted": 10, "non": 5, "prior": 35, "missed": 2.35, "wrong": 25, "mix": 11, "temp": 1.1, "gel": 2.2, "data": 4 }, {...} }]; 

I pull the data pairs I need for the specific line in the chart using the map() method:

var dataPairs = jsonFile.profiles.map(function(e) { return '{x:' + e.time + ', y:' + e.fitted + '}'; });

And then I tried to format it like an array needed for Chart.js

var dataPairs2 = '[' + dataPairs + ']';

So for the chart data line, I would call dataPairs2 . After looking at console.log(dataPairs2) , I realized it's not being treated as an array. dataPairs is and array, but each entry is a string, so calling that instead for the data line doesn't work either.

So, I'm trying to figure out how to convert dataPairs2 into an array. JSON.Parse() doesn't seem to work because it's not a standard format (I'm guessing), and I don't think I can use split() with commas as a delimiter because each array entry contains a comma.

Just format them in such a way in a first call to map. Instead of using map to produce array of stings, use it to produce array of objects.

jsonFile.profiles.map(v => ({ x: v.time, y: v.fitted }) );

 var jsonFile = { "profiles": [ { "time": 0, "conc": 0.15, "fitted": 0.1, "non": 0, "prior": 30, "missed": 2.9, "wrong": 2.9, "mix": 0.15, "temp": 0.015, "gel": 0.03, "data": 4 }, { "time": 1, "conc": 11, "fitted": 10, "non": 5, "prior": 35, "missed": 2.35, "wrong": 25, "mix": 11, "temp": 1.1, "gel": 2.2, "data": 4 } ]}; const d = jsonFile.profiles.map(v => ({ x: v.time, y: v.fitted }) ); console.log(d); 

I'm not sure if that's what you're looking for but you could simply return an Object instead of a String . Therefore return:

{x: e.time, y: e.fitted}

instead of:

'{x:' + e.time + ', y:' + e.fitted + '}'

in your mapping.

Here is the code:

 const jsonFile = {profiles:[{time:0,conc:.15,fitted:.1,non:0,prior:30,missed:2.9,wrong:2.9,mix:.15,temp:.015,gel:.03,data:4},{time:1,conc:11,fitted:10,non:5,prior:35,missed:2.35,wrong:25,mix:11,temp:1.1,gel:2.2,data:4}]}; const dataPairs = jsonFile.profiles.map(e => ({x: e.time, y: e.fitted}) ) console.log(dataPairs) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM