按日期参数删除对象。

时间:2016-08-05 15:00:31

标签: javascript

如何删除txnDate不在当前起始年01/01/2016 till current date 08/05/2016.

的对象
[{
    "site": "One",
    "txnDate": "01/19/2015",
   }, {
    "site": "Two",
    "txnDate": "01/25/2016",   
}, {
    "site": "Three",
    "txnDate": "01/26/2014",    
}, {
    "site": "Three",
    "txnDate": "09/05/2016",    
}]

我希望数组只包含一个对象。

[{
    "site": "Two",
    "txnDate": "01/25/2016",   
}]

我不知道如何处理这个问题,通常我会通过dateFrom和dateTo进行过滤...

arr.filter(function (el) {
   return el.txnDate <= "01/01/2016" &&
             el.txnDate >= "08/05/2016";
});

3 个答案:

答案 0 :(得分:4)

你快到了:

var arr = [{
    "site": "One",
    "txnDate": "01/19/2015",
   }, {
    "site": "Two",
    "txnDate": "01/25/2016",   
}, {
    "site": "Three",
    "txnDate": "01/26/2014",    
}, {
    "site": "Three",
    "txnDate": "09/05/2016",    
}];

var startTs = (new Date(new Date().getFullYear(), 0, 1)).getTime(),
    endTs = Date.now();

var res = arr.filter(function (el) {
  var ts = (new Date(el.txnDate)).getTime();
  return ts >= startTs && ts <= endTs;
});

console.log(res);

答案 1 :(得分:2)

JavaScript中的日期可以轻松地与&gt;进行比较。 =等运算符,因为它们在比较时被强制转换为数字。将您的值解析为日期并且您已经获得它:

&#13;
&#13;
var arr = [{
    "site": "One",
    "txnDate": "01/19/2015",
   }, {
    "site": "Two",
    "txnDate": "01/25/2016",   
}, {
    "site": "Three",
    "txnDate": "01/26/2014",    
}, {
    "site": "Three",
    "txnDate": "09/05/2016",    
}];

var arr = arr.filter(function (el) {
  var date = Date.parse(el.txnDate);
   return date >= new Date("01/01/2016") && date <= new Date();
});
console.log(arr.length);
console.log(arr[0])
&#13;
&#13;
&#13;

答案 2 :(得分:2)

实际上你非常接近,你需要首先将字符串解析为实际的Date对象进行比较。如果为下边界和上边界创建变量也会更容易。

const myDates = [{
    "site": "One",
    "txnDate": "01/19/2015",
   }, {
    "site": "Two",
    "txnDate": "01/25/2016",   
}, {
    "site": "Three",
    "txnDate": "01/26/2014",    
}, {
    "site": "Three",
    "txnDate": "09/05/2016",    
}];

//Upper and lower ranges.
const lowerDate = new Date(2016, 00, 01);
const upperDate = new Date(Date.now());

const goodDates = myDates.filter(item => {
  const currentDate = new Date(item.txnDate); //Current date object
  return lowerDate <= currentDate && currentDate <= upperDate //Only add things within our range
});

console.log(goodDates);

请注意,我为每个变量/对象使用了const。这确保了对象不能在以后变异,确保它们被设置。如果您希望它们是可变的(可更改的),请将变量声明更改为let