如何根据月份过滤数据

时间:2019-09-17 12:10:38

标签: javascript

我正在尝试过滤掉所有8个月的数据

我尝试了以下方法

https://jsfiddle.net/n2fypquz/2/

var json = [{
    "empId": 175,
    "Name": "Sai",
    "Sal": 37000,
    "doj": "2019-08-15 00:00:00"
  },
  {
    "empId": 1751,
    "Name": "Pavan",
    "Sal": 57000,
    "doj": "2019-07-15 00:00:00"
  }
];

var month = '8';

let empData = json.filter(function(mgmtmrktshare) {
  let date = mgmtmrktshare.doj;
  let afterSplit = date.split("-");
  return afterSplit[1] == month;
});

console.log(empData.length)

4 个答案:

答案 0 :(得分:2)

每当处理日期值时,最好使用Date对象。

注意::JS中的月份以0开头,因此1月为0,9月为8

var json = [{
    "empId": 175,
    "Name": "Sai",
    "Sal": 37000,
    "doj": "2019-08-15 00:00:00"
  },
  {
    "empId": 1751,
    "Name": "Pavan",
    "Sal": 57000,
    "doj": "2019-07-15 00:00:00"
  }
];

var month = '8';

let empData = json.filter(({
  doj
}) => (new Date(doj)).getMonth() === month - 1);

console.log(empData.length)

答案 1 :(得分:0)

您可以从时间戳中切出想要的部分,并获取一个数值,然后与月份进行比较。

var json = [{ empId: 175, Name: "Sai", Sal: 37000, doj: "2019-08-15 00:00:00" }, { empId: 1751, Name: "Pavan", Sal: 57000, doj: "2019-07-15 00:00:00" }],
    month = '8',
    empData = json.filter(({ doj }) => +doj.slice(5, 7) == month);

console.log(empData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

只需使用parseInt(afterSplit[1],'10')

var json = [{
    "empId": 175,
    "Name": "Sai",
    "Sal": 37000,
    "doj": "2019-08-15 00:00:00"
  },
  {
    "empId": 1751,
    "Name": "Pavan",
    "Sal": 57000,
    "doj": "2019-07-15 00:00:00"
  }
];

var month = '8';

let empData = json.filter(function(mgmtmrktshare) {
  let date = mgmtmrktshare.doj;
  let afterSplit = date.split("-");
  return parseInt(afterSplit[1], 10) == month;
});

console.log(empData.length)

答案 3 :(得分:0)

您可以使用以下代码。

var json = [{
    "empId": 175,
    "Name": "Sai",
    "Sal": 37000,
    "doj": "2019-08-15 00:00:00"
  },
  {
    "empId": 1751,
    "Name": "Pavan",
    "Sal": 57000,
    "doj": "2019-07-15 00:00:00"
  }
];

var month = '8'
function search(month, json){
    for (var i=0; i < json.length; i++) {
        if ((json[i].doj).getMonth() === month - 1) {
            return json[i];
            console.log(json[i])
        }
    }
}