我正在尝试根据日期过滤数组。
var items = [
{
createdBy: "suriyan"
product: "tv"
from: "2019-10-15T18:30:00.000Z"
to: "2019-10-29T18:30:00.000Z"
},
{
createdBy: "suriyan"
product: "phone"
from: "2019-10-19T18:30:00.000Z"
to: "2019-10-29T18:30:00.000Z"
}
]
filtered:[];
for(let i=0;i<this.items.length;i++){
const now = new Date();
if(now>this.items[i].from){
this.filtered.push(this.items[i])
}
}
console.log(this.filtered);
但这对我不起作用。有人可以帮我吗预先感谢
答案 0 :(得分:0)
您正在将Date与一个String
值进行比较,因此首先将其转换为Date
然后进行比较:
if(now > new Date(this.items[i].from){
this.filtered.push(this.items[i])
}
使用RxJS,您无需循环,因此也请尝试以下操作:
var items = [{
createdBy: "suriyan",
product: "tv",
from: "2019-10-15T18:30:00.000Z",
to: "2019-10-29T18:30:00.000Z",
},
{
createdBy: "suriyan",
product: "phone",
from: "2019-10-21T18:30:00.000Z",
to: "2019-10-29T18:30:00.000Z",
}
]
filtered = [];
const now = new Date();
this.filtered = items.filter(item => now > new Date(item.from));
console.log(this.filtered);
答案 1 :(得分:0)
尝试一下。您可以直接使用Array.filter()。将new Date()
转换为ISO
var items = [{
createdBy: "suriyan",
product: "tv",
from: "2019-10-15T18:30:00.000Z",
to: "2019-10-29T18:30:00.000Z",
},
{
createdBy: "suriyan",
product: "phone",
from: "2019-10-19T18:30:00.000Z",
to: "2019-10-29T18:30:00.000Z",
}
]
let data = items.filter(ele => ele.from > new Date().toISOString());
console.log(data)
console.log(new Date().toISOString())// current date time
答案 2 :(得分:0)
var items = [{
createdBy: "suriyan",
product: "tv",
from: "2019-10-15T18:30:00.000Z",
to: "2019-10-29T18:30:00.000Z",
},
{
createdBy: "suriyan",
product: "phone",
from: "2019-10-19T18:30:00.000Z",
to: "2019-10-29T18:30:00.000Z",
}
]
let data = items.filter(ele => new Date().toISOString() > ele.from);
console.log(data)
答案 3 :(得分:-1)
一心一意
const items = [
{
createdBy: 'suriyan',
product: 'tv',
from: '2019-11-15T18:30:00.000Z',
to: '2019-11-29T18:30:00.000Z',
},
{
createdBy: 'suriyan',
product: 'phone',
from: '2019-10-19T18:30:00.000Z',
to: '2019-10-29T18:30:00.000Z'
}
];
items.sort((a, b) => {
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.from) - new Date(a.from);
});
console.log(items);