bixente57 bixente57 - 11 days ago 5
Javascript Question

Data manipulation in DataTables

I have a quite complex data manipulation to perform.

My datasource gives me a list of cashflows, grouped by person like that:

{
"months": [
"2016-10-01",
"2016-11-01",
"2016-12-01",
"2017-01-01"
],
"persons": [
{
"label": "John",
"cashflows": [
{
"date": "2016-10-01",
"amount": "1000.00"
},
{
"date": "2016-11-01",
"amount": "1000.00"
}
]
},
{
"label": "Brad",
"cashflows": [
{
"date": "2017-01-01",
"amount": "5540.00"
}
]
}
]
}


I want to put those data in a DataTable, but I don't know how to "JOIN" the months and the cashflows.

My best guest is a sql-like query, but in javascript, in order to perform this pseudo-code:

select each person
for each person
good_row = person.cashflows LEFT JOIN months ON cashflows.date (iiish..)


I have set up a jsfiddle here.

Answer

Here is the plain javascript way to do it (the hard way). Fiddle link: https://jsfiddle.net/ngwqfjo0/

function getDesiredData() {
  var persons = real_data["persons"];
  var months = real_data["months"];

  persons.forEach(function(person) {
    var row = [];
    var amounts = [];
    row.push(person["label"]);

    months.forEach(function(month) {
      var amount = '';
      for(x = 0; x < person["cashflows"].length; x++) {
        if(month == person["cashflows"][x]["date"]) {
          amount = person["cashflows"][x]["amount"];
          break;
        }
      }
      amounts.push(amount);
    });

    desiredData.push(row.concat(amounts));

  });

  return desiredData;

}

To make life easier, consider using a functional utility like lodash or underscore

function getDesiredDataEasy() {
  var persons = real_data["persons"];
  var months = real_data["months"];
  var desiredData = [];

  return _.map(persons, function(person) {
    return _.concat([person["label"]], _.map(months, function(month) {
      var cashFlowDate = _.find(person["cashflows"], function(cf) {
        return cf.date == month;
      });
      return cashFlowDate ? cashFlowDate.amount : "";
    }));
  });
}