If you preprocess your JSON data before using it for printing you can lower your number of nested _.each
.
You will still have to use two _.each
statements to display your data.
The real benefit of doing this, is that you can centralize your data processing and you decouple your data from your display by adding a level of abstraction. If your data structure change overtime, you would only have to modify the data processing part and your "view" would remain the same
var headers = [];
var content = [];
var rows = 0;
_.each(slides, function(slide){
if (rows % 2 == 0) {
content.push([])
}
_.each(slide.months, function(month) {
if (_.isObject(month)) {
_.each(month, function(value, key) {
headers.push(key);
content[content.length - 1].push(value);
})
}
rows += 1;
})
});
console.log(headers);
console.log(content);
The headers
part would be the months label and the content
part would contain all your rows of data in the form of nested arrays of data.
* I used a row counter to merge the two parts of the year (from slide0 and slide1) with a modulus, but you might have to add some validation for this section to make sure you remain coherent in your table