Ryuzaki98
Ryuzaki98

Reputation: 35

Retrieving keys from a json array file(dynamically) and use it for d3js functions

I want to retrieve keys from external json array dynamically and use them in d3js functions which generates bar charts. Here is the json code.

[
 {   
    "Interns": 5,
    "Projects": 10,
    "Time":"Jan"
},

{
    "Interns": 16,
    "Projects": 20,
    "Time":"Feb"
}
]

I want to retrieve all the keys and use them in d3 functions which uses data to draw bars in bar chart.Below, an example I wrote d.Time but what if I don't know what keys i have been given??

x.domain(data.map(function(d) { return d.Time; }));

here is what i tried, this functions stores the keys in an array mykeys. The data in getKeys(data) refers to parameter from 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); // Gives ["Interns","Projects","Time"]

Now if i use console.log mykeys[2] it displays Time but when i use d.mykeys[2] in the above domain function, it doesn't seem to work ?? why so ??? Please help !

Upvotes: 0

Views: 40

Answers (1)

Holger Will
Holger Will

Reputation: 7526

your are trying to access a property of d by it's name as a string. mykeys[2] holds that string ("Time"), so it should be d[mykeys[2]] which is equal to d["Time"] which in turn is equal to d.Time ...

Upvotes: 2

Related Questions