SamLiu SamLiu - 5 months ago 24
JSON Question

Parse Json or Mongodata into viz.js dataset using x y coordinate?

My Json data is like this:

[ {
"age": 21,
"eyeColor": "blue",
"name": "Dejesus Thornton",
"gender": "male",
"registered": "2015-06-10"
},
{
"age": 21,
"eyeColor": "blue",
"name": "Dejesus Thornton",
"gender": "male",
"registered": "2015-06-11"
},
{
"age": 21,
"eyeColor": "blue",
"name": "Dejesus Thornton",
"gender": "male",
"registered": "2015-06-12"
},
...
]


I parsed it into my meteor mongo collection which is like this (every item in collection is an object):

{
"age": 21,
"eyeColor": "blue",
"name": "Dejesus Thornton",
"gender": "male",
"registered": "2015-06-11"
}


I was trying to parse this kind of data into viz.js which accepts data like this:

var items = [
{x: '2014-06-13', y: 30, group: 0},
{x: '2014-06-14', y: 10, group: 0},
{x: '2014-06-15', y: 15, group: 1},
{x: '2014-06-16', y: 30, group: 1},
{x: '2014-06-17', y: 10, group: 1},
{x: '2014-06-18', y: 15, group: 1}
];


I am trying to count how many people registered at the same day or have same eye color(same thing).

Answer

It's simple. Use Array.prototype.reduce() for counting. Assign your raw data array to a variable named rawArray.

var rawArray = [ {
    "age": 21,
    "eyeColor": "blue",
    "name": "Dejesus Thornton",
    "gender": "male",
    "registered": "2015-06-10"
  },
{
    "age": 21,
    "eyeColor": "blue",
    "name": "Dejesus Thornton",
    "gender": "male",
    "registered": "2015-06-11"
  },
{
    "age": 21,
    "eyeColor": "blue",
    "name": "Dejesus Thornton",
    "gender": "male",
    "registered": "2015-06-12"
  },
...
]

Then, group by specific property of each item. Like this:

function groupByProperty(array, property) {
  var newObject = array.reduce(function(counters, item) {
    if(!counters[item[property]]) {
      counters[item[property]] = 1;
    }
    else {
      counters[item[property]] += 1;
    }
    return counters;
  }, {});
  return Object.keys(newObject).map(function(x) {
    var obj = {
      x: x,
      y: newObject[x],
      group: 0
    };
    return obj; 
  });
}

console.log(groupByProperty(rawArray, 'registered')); // Group by 'registered'.

//  [ {
//    group: 0,
//    x: "2015-06-10",
//    y: 1
//  }, {
//    group: 0,
//    x: "2015-06-11",
//    y: 1
//  }, {
//    group: 0,
//    x: "2015-06-12",
//    y: 1
//  }]

console.log(groupByProperty(rawArray, 'eyeColor')); // Group by 'eyeColor'.

//  [{
//    group: 0,
//    x: "blue",
//    y: 3
//  }]