Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all the values for a given key, in an array of objects, using JavaScript and/or D3.js

I'm building a dashboard that uses D3.js for charts. I have a large array of objects. Each object has 32 key value pairs, with the same keys. Doesn't anyone know a good way to get all the values for a given key?

EDIT: As soon as I asked the question a simple function came to me. Also thought maybe a function already existed that I wasn't finding.

function getValues(data, key){
  var values = [];

  data.forEach(function(d){
    var v = d[key];

    if(!d3.set(values).has(v)){
      values.push(v);
    }
  })

  return values;
}
like image 252
user3226861 Avatar asked Mar 12 '14 14:03

user3226861


1 Answers

If you're already using d3, take a look at Mike Bostock's "Underscore Equivalents" gist: https://gist.github.com/mbostock/3934356

So

data.map(function(d) { return d[key]; });

will get you all the values. If you only want unique values, use

d3.set(data.map(function(d) { return d[key]; })).values());
like image 96
Joshua Romero Avatar answered Oct 05 '22 01:10

Joshua Romero