简体   繁体   English

检查带有对象的数组是否包含JS中的对象

[英]Check if array with objects contains an object in JS

I'm trying to write a function that will make it easy to know if a specific object key/value is contained within another array with objects. 我正在尝试编写一个函数,该函数将使您很容易知道另一个对象数组中是否包含特定的对象键/值。

I've tried indexOf but that doesn't seem to do the trick. 我已经尝试过indexOf,但这似乎并不能解决问题。 Example: 例:

if(data2.indexOf(data1) > 0){
    console.log("Found!");
    return true;
  }else{
    return false;
  }

Here is the object: 这是对象:

  {
    "movie": {
      "ids": {
        "imdb": "tt2975590"
      }
    }
  }

I need a function that can tell me if it's already in another array like this one: 我需要一个函数来告诉我它是否已经在另一个数组中,例如:

[
  {
    "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
      }
    }
  }
]

In this case it would be and return true. 在这种情况下,它将为true并返回true。 (the movie Batman v Superman has the same imdb id). (电影《蝙蝠侠对超人》的imdb ID相同)。

Any help? 有什么帮助吗? Thanks! 谢谢! :D :D

To clarify you got an array that contains objects . 为了澄清,您得到了一个包含对象数组 You should take a look at Array.prototype.some , which will iterate over an array and return true if true is returned from inside the callback. 您应该看一下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;
});

Where arr is the array of movies. 其中arr是电影数组。

You can use dot notation and bracket notation to access properties in an object, eg: search.movie and search['movie'] will return: 您可以使用点符号和方括号符号来访问对象中的属性,例如: search.moviesearch['movie']将返回:

{
  "ids": {
    "imdb": "tt2975590"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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