I am looking to dynamically retrieve keys from an external JSON array and utilize them in d3js functions to create bar charts. Below is the JSON code provided:
[
{
"Interns": 5,
"Projects": 10,
"Time":"Jan"
},
{
"Interns": 16,
"Projects": 20,
"Time":"Feb"
}
]
My goal is to extract all keys and integrate them into d3 functions that are responsible for generating bars in a bar chart. In the example written below, d.Time
is used, but I may not always know which keys have been supplied:
x.domain(data.map(function(d) { return d.Time; }));
To address this issue, I attempted to create a function that stores the keys in an array called myKeys
. The data
parameter in getKeys(data)
pertains to the input from the d3.json()
function:
var getKeys = function(arr) {
var key, keys=[];
for(var i=0; i< (arr.length - (arr.length - 1)); i++) {
for(key in arr[i]) {
keys.push(key);
}
}
return keys;
}
var myKeys = getKeys(data); // Returns ["Interns","Projects","Time"]
When I use console.log myKeys[2]
, it correctly outputs Time
. However, when attempting to use d.myKeys[2]
within the domain function above, it does not produce the desired outcome. Can anyone shed some light on why this might be happening? Your assistance would be greatly appreciated!