How to map over a object

How to map over a object
0

here’ s im using react useEffect hook :point_down:

  useEffect(() => {
    if (favImdbList.length > 0) {
      const moviesInfo = [];
//favImdbList is an array of imdb movieid
      favImdbList.map(id => {
        (async () => {
          const { data } = await axios.get(
            `http://www.omdbapi.com/?apikey=secret&i=${id}`
          );
          moviesInfo.push(data);
        })();
      });

      console.log("test");
      moviesInfo.map(m => console.log(m.Title)); //why this isnt working??
      console.log(moviesInfo);
      console.log(moviesInfo[0]);
    }
 
  }, [favImdbList]);

here’s screenshot of my console why mapping wont work . so how can i map through this object please help me i dont get how to iterate this .
image

and data object looks like this

map takes an array and produces another array of the same size by applying the function you give it as a callback to each one.

function times2 (n) {
  return n * 2;
}

[1,2,3].map(times2)
// This returns [2,4,6]

So for this line:

moviesInfo.map(m => console.log(m.Title))

You are trying to mapping each value in moviesInfo to whatever console.log returns (it’s always undefined, so you’re just mapping every value to undefined). for each is what you use, but in this case it really isn’t what you want, just want to see what your thinking behind the code is

You are doing something wierd here, and I think you’re misunderstanding both how map works, and how to deal with async fetching of data in JS.

Can your explain the code you’ve written here, what you think it is doing?

1 Like

im trying to retrieve details of a movie using their imdbId. favImdbList is an array has user favorite movie ids as Strings. so im mapping through each id and retreiving the data from omdbapi and pushing data Object inside the moviesInfo array but now how to iterate this ?? foreach is also not working

  • Map isn’t a general iterator, you don’t push to another thing
  • forEach you do,
  • either can be used, but this is async so you need to be a bit more careful doing it
  • probably easiest to either use Promise.all on an array of fetches (will aim to resolve all of them and produces an array of results)
  • or use a for await…of loop to get sequentially.
  • or ids.map(async (id) => await // fetch call)
const API_BASE = "http://www.omdbapi.com/?apikey=secret&i=";

const fetchMovies1 = async () => {
  const movieFetches = favImdbList.map(id => axios.get(`${API_BASE}${id}`);
  const movies = await Promise.all(movieFetches);
  console.log(movies);
};

const fetchMovies2 = async () => {
  const movies = [];
  for await (const id of favImdbList) {
    const { data } = await axios.get(`${API_BASE}${id}`);
    movies.push(data);
  }
  console.log(movies);
}

fetchMovies1();
fetchMovies2();
1 Like

should be movies.push(data)

1 Like