Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change JSON data to Javascript array of objects with D3

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);
   });
like image 763
JaapNiks Avatar asked Apr 19 '26 17:04

JaapNiks


1 Answers

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 = /(?:[A-Z])/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()
}
like image 166
Rajesh Avatar answered Apr 21 '26 06:04

Rajesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!