I have an object which contains an array which looks like this:
{
"media": [
{
"title": "Raiders of the Lost Ark",
"year": "1981",
"poster": "http://ia.media-imdb.com/images/M/MV5BMjA0ODEzMTc1Nl5BMl5BanBnXkFtZTcwODM2MjAxNA@@._V1_SY1000_CR0,0,664,1000_AL_.jpg",
"genre": ["action", "adventure"],
"type": "movie"
},
{
"title": "The Other Guys",
"year": "2010",
"poster": "http://ia.media-imdb.com/images/M/MV5BMTc0NDQzNTA2Ml5BMl5BanBnXkFtZTcwNzI2OTQzMw@@._V1_.jpg",
"genre": ["action", "comedy", "crime"],
"type": "movie"
}
]
}
I'm trying to create a filter function which will return all the items with a certain genre.
Here's the filter I made but doesn't seem to return any values.
//pretend movies equals my parsed JSON file
const Movies = json.media;
const Filter = function(array, key, value){
let i, j, filteredResults = [], item;
for(i = 0, j = array.length; i<j; i++){
item = array[i];
if(typeof item[key] !== "undefined" && item[key] === value){
filteredResults.push(item);
}
}
return filteredResults;
}
console.log(Filter(Movies, "genre", "action"));
This returns no value but should return an array with the 2 movies in it?
Movies.filter(m => m.genre.includes('action'))item[key] === valuehere you're comparing an array with a string.if. Break on that line, and examine the variablesitem[key]andvalueand you should be able to see why the condition is not being met.