Home > Net >  Getting a value from an object in an array of objects that matches a defined variable
Getting a value from an object in an array of objects that matches a defined variable

Time:10-27

Let's say I have this array of objects.

 const movieTitles = [
    {
      movieId: "4820",
      movieName: "The Planet Of The Apes",
    },
    {
      movieId: "0489",
      movieName: "Interstellar",
    },
    {
      movieId: "6238",
      movieName: "The Dark Knight",
    },
  ];

And an outside variable (that matches with the object with the Interstellar movie) const matchId = "0489";

My questions are:

  1. How could I check the array for the correct object that contains the matchId variable?

  2. How could I get that object and use it's properties (like movieName) once the ids have been confirmed to be the same?

  3. If the variable dynamically changed, how could I check whatever the variable is against the array of objects to check whether it does or doesn't match?

Thanks for the help in advance!

CodePudding user response:

If each movieId is unique, then you should use an object, not an array. Something like this is better:

const movieTitles = {
  "4820": {
    movieName: "The Planet Of The Apes",
  },
  "0489": {
    movieName: "Interstellar",
  },
  "6238": {
    movieName: "The Dark Knight",
  },
};

Note: If you cannot change the format movieTitles, then you can create a new object from the original array like this:

const movieTitles = [{
    movieId: "4820",
    movieName: "The Planet Of The Apes",
  },
  {
    movieId: "0489",
    movieName: "Interstellar",
  },
  {
    movieId: "6238",
    movieName: "The Dark Knight",
  },
];

const movieObject = {};
for (const movie of movieTitles) {
  const id = movie.movieId;
  delete movie.movieId;
  movieObject[id] = movie;
}

console.log(movieObject);

Either way you do it, you can then easily select the movie you need with the syntax movies[movieId]. Like this:

const movies = {
  "4820": {
    movieName: "The Planet Of The Apes",
  },
  "0489": {
    movieName: "Interstellar",
  },
  "6238": {
    movieName: "The Dark Knight",
  },
};

// You can use a static value, like this:
console.log(movies["0489"])

// Or a variable like this:
const movieId = "4820"; // change this to any movie ID
console.log(movies[movieId])

This is much faster than looping over the array and much more idiomatic. The time complexity of using an object is a one-time conversion of O(n), then O(1) for each access after that. In contrast, using .filter() is O(n) every time.

CodePudding user response:

Javascript array function filter would be the perfect fit to solve in your situation.

function hasItem(checkItem){
let isAvailable = movieTitles.filter((item)=> item.movieId==checkItem)
return isAvailable
}

console.log(hasItem('0489'))

//returns {
//     movieId: "0489",
//      movieName: "Interstellar",
//    }

The isAvailable will have the array of the condition matched.

  • Related