I have an array of objects that have a key attribute with the name of a country and a values attribute that is an array of values that contain data by year:
I needed the opposite: an array of objects where the key is the year and the values an array containing data for each country in the original array.
I wrote this script to remap it, but it feels like a huge hack to me. How can I do this in fewer lines of code and make it more readable?
self.dataByYear = []
$.each(self.dataByGroup, function(i,v) {
$.each(v.values, function(j,x) {
var inYears = self.dataByYear.filter(function(d) { return d.key == x.xgroup});
if (inYears.length > 0 ) {
if (self.dataByYear[j] !== undefined) {
self.dataByYear[j].values.push(x);
}
} else {
newObj = {};
newObj.key = x.xgroup;
newObj.values = [x];
self.dataByYear.push(newObj);
}
})
});