2016-10-12 128 views
1

這是我的JSON數據(這個文件是一個外部文件,被稱爲「data.json」)如何JSON數據更改爲對象的Javascript數組與D3

[ 
    { 
    "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); 
    }); 

回答

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

+0

我認爲這需要更多的處理。我建議使用'eachObjArr.push({axis:key,value:data [i] [d]});'另外maand是一個月的荷蘭語單詞,我認爲它應該被排除 – zfor

+1

更新了代碼。 – Thaadikkaaran

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

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在這裏幫助!