如何使用JSON格式的日期过滤数据 [英] How to filter the data using date from JSON format

查看:67
本文介绍了如何使用JSON格式的日期过滤数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用日期进行过滤,但数据为JSON格式.如何在JavaScript中使用日期过滤大型数据集?

I want to filter using date but the data is in JSON format. How can I filter the large dataset using date in JavaScript?

示例:

data=[{date:'22-12-2014',name:'selva'},{date:'10-10-2010',name:'raja'},{date:'11-11- 2011',name:'suresh'}]

推荐答案

要获取与特定日期匹配的元素集,可以使用

To grab the set of elements that match a certain date you can use filter to extract them into a new array.

function getByDate(date){
  return data.filter(function (el) {
    return el.date == date;
  });
}

var arr = getByDate('11-11-2011');

要按日期对数据集进行排序,您需要首先将日期字符串转换为JS日期对象.这涉及稍微调整日期字符串,以便可以对其进行正确解析.

To to sort your dataset by date you need to convert your date strings to a JS date object first. That involves adjusting the date string slightly so it can be parsed properly.

function reformatDate(date) {
  return arr = date.split('-').reverse();
}

var sortByDate = function (a, b) {
  return new Date(reformatDate(a.date)) - new Date(reformatDate(b.date));
};

data.sort(sortByDate);

JSFiddle演示

这篇关于如何使用JSON格式的日期过滤数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆