0

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

2
  • What have you already tried? Commented Jun 8, 2016 at 17:59
  • Updated my question with example and better explanation Commented Jun 8, 2016 at 18:06

1 Answer 1

1

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"
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you andlrc !! Works perfectly :D
@webslash I'm glad it worked, now time to read my answer twice, and rewrite it yourself :-) I also linked a few interesting reads.
Will do! Thanks again for the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.