D3/js Mapping A Json Data Callback
I have seen many examples with d3.csv() callback mappings such as: var data = raw_data.map(function(d) { return variable1 : +d.variable1, variable2 : +d.variable2 }); How
Solution 1:
Your .map()
does not match your JSON data. Your JSON consists of one array having one object containing three arrays for id
, xs
and ys
. To convert all those strings to numerical values you need three separate loops:
var obj = raw_json[0];
obj.id = obj.id.map(id => +id);
obj.xs = obj.xs.map(x => +x);
obj.ys = obj.ys.map(y => +y);
Or, preferably, since you do not need to create new arrays while only converting to numbers, you could also do the conversion on the spot using .forEach()
instead of .map()
.
const toNum = (d, i, a) => { a[i] = +d }; // Conversion functionvar obj = raw_json[0];
obj.id.forEach(toNum);
obj.xs.forEach(toNum);
obj.ys.forEach(toNum);
Have a look at the following working example:
var raw = `
[{
"id": ["1", "2", "3"],
"xs": ["11", "12", "13"],
"ys": ["21", "22", "23"]
}]
`;
var data = JSON.parse(raw);
consttoNum = (d, i, a) => { a[i] = +d }; // Conversion functionvar obj = data[0];
obj.id.forEach(toNum);
obj.xs.forEach(toNum);
obj.ys.forEach(toNum);
console.dir(data);
Post a Comment for "D3/js Mapping A Json Data Callback"