webslash
webslash

Reputation: 53

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. 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. (the movie Batman v Superman has the same imdb id).

Any help? Thanks! :D

Upvotes: 0

Views: 697

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47099

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.

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.

You can use dot notation and bracket notation to access properties in an object, eg: search.movie and search['movie'] will return:

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

Upvotes: 1

Related Questions