简体   繁体   English

按年份过滤 json 数据

[英]filtering json data by year

I am looking to filter out records that have a year between 2000 to 2021.我希望过滤掉 2000 年到 2021 年之间的记录。

"Rank": 50,
   "Title": "Casablanca",
   "Description": "A cynical nightclub owner protects an old flame and her husband from Nazis in Morocco.",
   "Runtime": 102,
   "Genre": "Drama",
   "Rating": 8.5,
   "Metascore": "100",
   "Votes": 441864,
   "Gross_Earning_in_Mil": "1.02",
   "Director": "Michael Curtiz",
   "Actor": "Humphrey Bogart",
   "Year": 1942

I have tried using a method I found from a different solution however it does not work correctly.我尝试使用从不同解决方案中找到的方法,但它无法正常工作。

var startDate = new Date("1990");
var endDate = new Date("2000");

var resultProductData = movies.filter(a => {
  var date = new Date(a.Year);
  return (date >= startDate && date <= endDate);
});

Creating Date objects is not gaining you anything here since the year property is already stored as an integer you can just compare it directly创建 Date 对象在这里没有任何好处,因为 year 属性已经存储为 integer 你可以直接比较它

const result = movies.filter(({year}) => (year >= 2000 && year =< 2021)); 

But the reason your filter isn't working is that you are creating the startDate and endDate dates from strings and the compare date from an integer.但是您的过滤器不起作用的原因是您正在从字符串创建startDateendDate日期,并从 integer 创建比较日期。 The strings are interpreted as years, while js interprets the integer as milliseconds since epoch time.字符串被解释为年,而 js 将 integer 解释为自纪元时间以来的毫秒数。

var startDate = new Date("1990");
// Mon Jan 01 1990 00:00:00 GMT+0000 (GMT)
var endDate = new Date("2000");
// Sat Jan 01 2000 00:00:00 GMT+0000 (GMT)

const a = { "Year": 1942 }
var date = new Date(a.Year);
// Thu Jan 01 1970 00:00:01 GMT+0000 (GMT)

To fix it you would need to cast your movie.year to a string.要修复它,您需要将您的movie.year转换为字符串。

var resultProductData = movies.filter(a => {
  var date = new Date(a.Year.toString());
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM