我试图编写一个函数,这样可以很容易地知道一个特定的对象键/值是否包含在另一个带有对象的数组中。
我试过了indexOf,但这似乎不起作用。示例:
if(data2.indexOf(data1) > 0){
console.log("Found!");
return true;
}else{
return false;
}这是一个对象:
{
"movie": {
"ids": {
"imdb": "tt2975590"
}
}
}我需要一个函数,它可以告诉我它是否已经在另一个数组中,比如这个:
[
{
"id": 2008588422,
"type": "movie",
"movie": {
"title": "Batman v Superman: Dawn of Justice",
"year": 2016,
"ids": {
"trakt": 129583,
"slug": "batman-v-superman-dawn-of-justice-2016",
"imdb": "tt2975590",
"tmdb": 209112
}
}
},
{
"id": 1995814508,
"type": "movie",
"movie": {
"title": "Dirty Grandpa",
"year": 2016,
"ids": {
"trakt": 188691,
"slug": "dirty-grandpa-2016",
"imdb": "tt1860213",
"tmdb": 291870
}
}
}
]在这种情况下,它将是并返回true。(电影“蝙蝠侠大战超人”也有同样的imdb id)。
有什么帮助吗?谢谢!:D
发布于 2016-06-08 18:04:23
为了澄清你得到了一个array that contains objects。您应该看看Array.prototype.some,它将在数组上迭代,如果从回调内部返回true,则返回true。
var search = {
"movie": {
"ids": {
"imdb": "tt2975590"
}
}
};
var found = arr.some(function(obj) {
return obj.movie.ids.imdb == search.movie.ids.imdb;
});其中arr是电影的数组。
您可以使用dot notation and bracket notation访问对象中的属性,例如:search.movie和search['movie']将返回:
{
"ids": {
"imdb": "tt2975590"
}
}https://stackoverflow.com/questions/37709660
复制相似问题