简体   繁体   中英

filtering json data by year

I am looking to filter out records that have a year between 2000 to 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

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. The strings are interpreted as years, while js interprets the integer as milliseconds since epoch time.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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