How to convert Json to Array In javascript for chart.js

๐Ÿ‘:0

You can try this

var data = [{"month":"January","name":"Alex","count":10},{"month":"February","name":"Alex","count":20},{"month":"February","name":"John","count":30},{"month":"February","name":"Mark","count":40},{"month":"March","name":"Alex","count":10},{"month":"March","name":"John","count":20}];

// TO FIND UNIQUE ARRAY
var months = data.map(function(t){ return t.month});
uniqueMonths = months.filter(function(item, pos) {
    return months.indexOf(item) == pos;
});
console.log('UNIQUE MONTHS:- '+uniqueMonths);

var names = data.map(function(t){ return t.name});
uniqueNames = names.filter(function(item, pos) {
    return names.indexOf(item) == pos;
});
console.log('UNIQUE NAMES:- '+uniqueNames);
var countArr = {};
uniqueNames.forEach(function(d){
	var arr = [];
	uniqueMonths.forEach(function(k){
		arr.push(getValue(d,k));
	});
	countArr[d] = arr;
});
console.log('COUNT ARRAY:- '+JSON.stringify(countArr));

// To get value from the array
function getValue(name, month){
	var value = 0;
	data.forEach(function(d){
		if(d.name == name && d.month == month){
			value = d.count;
		}
	});
	return value;
}

Leave a comment