0

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 !

0

1 Answer 1

2

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 ...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.