javascript - 数据表中的数据操作

标签 javascript jquery datatables

我要执行相当复杂的数据操作。

我的数据源为我提供了一份现金流列表,按这样的人分组:

{
  "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"
        }
      ]
    }
  ]
}

我想将这些数据放入数据表中,但我不知道如何“连接”月份和现金流。

我最好的客人是一个类似sql的查询,但是在javascript中,为了执行这个伪代码:

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

我已经设置了jsfiddle在这里。

最佳答案

这是简单的 JavaScript 方法(困难的方法)。 fiddle 链接: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;

}

为了让生活更轻松,请考虑使用像 lodash 这样的功能实用程序或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 : "";
    }));
  });
}

关于javascript - 数据表中的数据操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809252/

相关文章:

jquery - 如何使用 jQuery 检查所有复选框

javascript - 将引用编号传递给数据控制者

jquery - 如何使用JQuery动态向表添加数据

javascript - DataTables:获取所选单元格之前单元格的文本内容

JavaScript - 将数组索引分配给返回值不起作用

javascript - 如何在javascript中获取带有ID的选中复选框值

javascript - 类型 'any ' 的参数不可分配

jquery - 了解 $.validator.unobtrusive.adapters.addBool() 方法

Shiny 中的 R 大型数据表显示

javascript - 数组更改时不调用 AngularJs Formatter