Data manipulation in DataTables

2019-09-08 04:50发布

问题:

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.

回答1:

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 : "";
    }));
  });
}