【问题标题】:filtering json data by year按年份过滤 json 数据
【发布时间】:2021-03-24 01:09:25
【问题描述】:

我希望过滤掉 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

我尝试使用从其他解决方案中找到的方法,但它无法正常工作。

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);
});

【问题讨论】:

  • const result = movies.filter(({year}) =&gt; (year &gt; 2000 &amp;&amp; year &lt; 2021)); year 属性是整数,直接查看即可。
  • 您的过滤器不起作用的原因是您正在从字符串中生成 startDateendDate 日期,并且从整数中生成比较日期。字符串被读取为年,而整数 js 解释为自纪元时间以来的毫秒数。

标签: javascript json filter


【解决方案1】:

在这里创建 Date 对象并没有为您带来任何好处,因为 year 属性已经存储为整数,您可以直接比较它

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

但是您的过滤器不起作用的原因是您正在从字符串创建 startDateendDate 日期,并从整数创建比较日期。字符串被解释为年,而 js 将整数解释为自纪元以来的毫秒数。

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)

要修复它,您需要将 movie.year 转换为字符串。

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

【讨论】:

  • 没错,我通过手机添加的代码错过了字符串部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 2021-12-07
  • 2021-07-06
  • 2015-09-20
相关资源
最近更新 更多