JS:ObservableArray筛选

时间:2019-01-10 13:28:09

标签: javascript knockout.js

我有一个如下所示的observableArray,

var details = ko.observableArray([]);
details = [
      { AccName: "Jane Doe", ExpDt: '2019-01-10', Contract: "Trial" },
      { AccName: "John", ExpDt: '2018-12-30', Contract:  "Licensed"},
      { AccName: "Doe", ExpDt: '2018-09-10', Contract:  "Trial"}
];

因此,我需要根据ExpDt和Contract提取用户。

For Ex => ExpDt < today dt (2019-01-10) and having "trial" contract
Answer should be => Jane Doe

请给我一些建议。

1 个答案:

答案 0 :(得分:1)

使用Array#filterdestructuringString#splitSpread operatorDate.UTC

const details=[{AccName:"Jane Doe",ExpDt:"2019-01-10",Contract:"Trial"},{AccName:"John",ExpDt:"2018-12-30",Contract:"Licensed"},{AccName:"Doe",ExpDt:"2018-09-10",Contract:"Trial"}];

const res = details.filter(({ExpDt, Contract})=>{
  const darr = ExpDt.split("-");
  //Date.UTC accepts months from 0 - 11
  darr[1] = darr[1] - 1;
  return Date.UTC(...darr) < Date.now() && Contract === "Trial";
})

console.log(res);

您会得到两个结果,因为Doe也符合要求:

ExpDt: 2018-09-10 < 2019-01-10
Contract: Trial === Trial