This is my JSON data (this document is an external file and is called 'data.json')
[
{
"maand": "augustus 2014",
"weinigSlaap": "0.15",
"hogeStress": "0.1",
"langerReistijd": "0.12",
"hogeWerkdruk": "0.1",
"lageLiquiditeit": "0.1"
}
]
and I need it to become this with help of D3.
var data = [
[
{
axis: "Weinig slaap",
value: 0.15
}, {
axis: "Hoge stress",
value: 0.1
}, {
axis: "Lange reistijd",
value: 0.12
}, {
axis: "Hoge werkdruk",
value: 0.1
}, {
axis: "Lage liquiditeit",
value: 0.1
}
]
];
I'm stuck at this point and don't have any hope in live anymore ;)
d3.json('data.json', function (data) {
data.push(data);
console.log(data);
});
You can try something like this:
var data = [{ "maand": "augustus 2014", "weinigSlaap": "0.15", "hogeStress": "0.1", "langerReistijd": "0.12", "hogeWerkdruk": "0.1", "lageLiquiditeit": "0.1" }] var r = /(?:[AZ])/g; var keysToSkip = ["maand"] var result = []; data.forEach(function(d) { var keys = Object.keys(d).filter(x => keysToSkip.indexOf(x) === -1); var _o = keys.map(function(k) { var o = {}; var parsedVal = k.replace(r, function(s) { return " " + s }); return { axis: toTitleCase(parsedVal), value: d[k] } }) result.push(_o); }) console.log(result) function toTitleCase(str) { return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase() }
For you, Javascript alone is enough as shown below. Keep this code inside your d3.json success callback.
var data = [{ "maand": "augustus 2014", "weinigSlaap": "0.15", "hogeStress": "0.1", "langerReistijd": "0.12", "hogeWerkdruk": "0.1", "lageLiquiditeit": "0.1" }], mappedData = []; for (var i = 0; i < data.length; i++) { var eachObjArr = []; for (key in data[i]) { if (data[i].hasOwnProperty(key)) { var obj = {}; obj[key] = data[i][key]; eachObjArr.push({ axis: key, value: data[i][key] }); } } mappedData.push(eachObjArr); } for (var i = 0; i < mappedData.length; i++) { console.log(mappedData[i]); }
With Object.keys
you can iterate through keys of the object, and this is what you get:
var d = { "maand": "augustus 2014", "weinigSlaap": "0.15", "hogeStress": "0.1", "langerReistijd": "0.12", "hogeWerkdruk": "0.1", "lageLiquiditeit": "0.1" } var r = Object.keys(d).map(k => ({ axis: k.replace(/[AZ]/g, l => (' ' + l.toLowerCase())), value: Number(d[k]) })) console.log(r)
clearly es6 helps here !
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.