[英]Get an Object in an Array that has a property which is an Array that contains a matching value
I have an Array of Objects with a structure like this: 我有一个具有这样的结构的对象数组:
[
{
title: "",
imagePoster: "",
episodes: "",
score: "",
genres: ["Comedy", "Drama", ...],
description: ""
},
...
]
I need to return an Object which contains specific value like "Comedy"
in the genres
Array. 我需要返回一个genres
数组中包含特定值(例如"Comedy"
的对象。 I've been trying a lot of ways like for
, filter
, map
, indexOf
... But, I still can't figure it out, unless I search for ["Comedy", "Drama", ...]
(ie, the whole Array). 我一直在尝试很多方法,例如for
, filter
, map
, indexOf
...。但是,除非我搜索["Comedy", "Drama", ...]
(即,整个数组)。
You could use Array#find
to find the first element that satisfies the condition: 您可以使用Array#find
查找满足条件的第一个元素:
const search = "Comedy";
const found = array.find(obj => obj.genres.includes(search));
This also uses Array#includes
which checks if the argument, the search keyword, exists in the genres
array of each object. 它还使用Array#includes
来检查参数(搜索关键字)是否存在于每个对象的genres
数组中。 And if you needed IE support, use Array#indexOf
and check if the return value is greater than -1 instead which does exactly the same thing: 并且如果需要IE支持,请使用Array#indexOf
并检查返回值是否大于-1,而返回值是否完全相同:
obj => obj.genres.indexOf(search) > -1
And if you wanted to return all objects that have a certain genre, not just the first one, filter the array with Array#filter
which filters the array based on a condition: 并且,如果您想返回所有具有特定类型的对象,而不仅仅是第一个,请使用Array#filter
过滤该数组,后者根据条件过滤该数组:
const search = "Comedy";
const found = array.filter(obj => obj.genres.includes(search));
This will filter the array and only leave the objects that include the search keyword in their genres
array. 这将过滤数组,仅将包含搜索关键字的对象保留在其genres
数组中。 Again, you can swap out includes
for the indexOf
check, and you can always just access the first element of the filtered array if find
is not supported on your target browsers (namely IE). 同样,您可以将includes
换为indexOf
检查,并且如果目标浏览器(即IE)不支持find
则始终可以仅访问过滤后的数组的第一个元素。
Array.find
& Array.includes
are your friends. Array.find
和Array.includes
是您的朋友。 There are also polyfills for non-browsers :) 也有非浏览器的polyfills :)
The most supported way would be to use Array.filter
& Array.indexOf
最受支持的方法是使用Array.filter
和Array.indexOf
function getMovieByGenre(genre) {
return movies.filter(function(movie) {
return movies.genres.indexOf(genre) >= 0
})[0];
}
var someComedy = getMovieByGenre('Comedy');
if (someComedy) {
// movie found
}
I am using the most supported code, without polyfills and ES6 features 我使用的是最受支持的代码,没有polyfills和ES6功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.