如何使用D3将JSON数据更改为Javascript对象数组

时间:2016-10-12 13:07:48

标签: javascript json d3.js

这是我的JSON数据(此文档是外部文件,名为'data.json')

[
    {
    "maand": "augustus 2014",
    "weinigSlaap": "0.15",
    "hogeStress": "0.1",
    "langerReistijd": "0.12",
    "hogeWerkdruk": "0.1",
    "lageLiquiditeit": "0.1"
    }
]

我需要它在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
        }
    ]
];

我已经陷入困境,对生活没有任何希望了;)

  d3.json('data.json', function (data) {
      data.push(data);
      console.log(data);
   });

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:



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()
}




答案 1 :(得分:0)

对于您来说,仅使用Javascript就足够了,如下所示。将此代码保留在d3.json成功回调中。

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]);
}

答案 2 :(得分:0)

使用Object.keys,你可以遍历对象的键,这就是你得到的:

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(/[A-Z]/g, l => (' ' + l.toLowerCase())),
     value: Number(d[k]) 
}))
                           
console.log(r)

显然es6在这里有帮助!