0

For example, JSON element, where the "categories" field is an array:

{"city": "San Francisco, CA", "business_id": "15", "name": "Parastructure", "date":  "2014", "founder_education": "Stanford", "categories": ["Big Data", "Big Data Analytics", "Data Visualization", "Enterprise Software"], "Amount": "500000000"}

Using dc.js, how would I go about selecting each element in the array and adding it to the chart visualization?

var categories = ndx.dimension(function (d) {
     return d.categories; // this wouldn't work

});

var categoriesGroup = categories.group();
Victor M
  • 27
  • 8
  • 1
    possible duplicate of [Is there a way to tell crossfilter to treat elements of array as separate records instead of treating whole array as single key?](http://stackoverflow.com/questions/17524627/is-there-a-way-to-tell-crossfilter-to-treat-elements-of-array-as-separate-record) – Gordon Jun 20 '14 at 02:15
  • That thread didn't really answer my question in a concise way – Victor M Jun 20 '14 at 02:22
  • There isn't a concise answer. You have to hack around it. See also https://github.com/dc-js/dc.js/issues/535 and https://github.com/square/crossfilter/issues/5. It would be great to create some utilities to make this easier. – Gordon Jun 20 '14 at 02:29
  • 1
    You could also flatten your data so that each category gets its own row. – Gordon Jun 20 '14 at 02:31
  • How would I go about flattening it? – Victor M Jun 20 '14 at 02:35

1 Answers1

0

Crossfilter works best with a flat arrays of records. If you don't like the idea of a reduce function creating maps, as suggested in the comments above, you can create a flat array out of your data basically by "multiplying out" the categories with the records.

So, something like this (using underscores's clone function to duplicate the records):

var product = [];
for(var r in records) {
    for(var i = 0; i < r.categories.length; ++i) {
        var r2 = _.clone(r);
        delete r2.categories;
        r2.category = r.categories[i];
        product.push(r2);
    }
}

(Warning: not tested.) Now, where you used to have n categories in a record, you'll have n records, one for each category. And you can reduce on category okay now.

... Of course it might make your other calculations messy or not work (some hints here), which is why I suggested the other answer first. Unfortunately crossfilter was not designed for dealing with multi-valued fields.

Community
  • 1
  • 1
Gordon
  • 19,811
  • 4
  • 36
  • 74