Home > other >  JSON keys for a movie title have different names
JSON keys for a movie title have different names

Time:01-02

Trying to fetch data from TMDb (The movie database), when I iterate through an array of objects to get the movie titles, some objects have the key name for movie name as original_title, but in other objects the movie name is original_name. So when I iterate through the objects some of the movie titles just come back as undefined.

const APIKey = <api_key>;
const APIUrl = "https://api.themoviedb.org/3/trending/all/day?api_key=<api_key>&page=1"
const imagePath = "https://image.tmdb.org/t/p/w500"

getTrendingMovieData(APIUrl);
async function getTrendingMovieData(url) {
    const resp = await fetch(url);
    const data = await resp.json();
    console.log(data.results);
    showTrendingMovies(data.results);
};

function showTrendingMovies(movies) {
movies.forEach(movie => {
    trending = document.createElement("div");
    trending.classList.add('movie');
    const { id, original_title, release_date } = movie;
    trending.innerHTML = `
    <img src="${imagePath   movie.poster_path}" alt="${id}">
    <div >
        <p id="title">${original_title}</p>
        <div >
            <p>${release_date}<span>Thriller</span></p>
        </div>
        <div >
            <i  id="star"></i><p>7.4 <span>(85,000)</span></p>
        </div>
    </div> 
    `;
    document.getElementById("trending-movies").appendChild(trending);
    });
};

When I try with original_title it works except the objects that have key original_name just returns undefined. Whereas if I try with original_name I get an

Uncaught (in promise) ReferenceError: original_name is not defined.

CodePudding user response:

You can try something like this.

const { id, original_title, original_name, release_date } = movie;
trending.innerHTML = `
<img src="${imagePath   movie.poster_path}" alt="${id}">
<div >
    <p id="title">${original_title || original_name}</p>
    <div >
        <p>${release_date}<span>Thriller</span></p>
    </div>
    <div >
        <i  id="star"></i><p>7.4 <span>(85,000)</span></p>
    </div>
</div> 
`;

it will simply use original_name if the original_title is undefined

CodePudding user response:

Because some objects have the key name for the movie name as original_title, and for other objects, the movie name is original_name.

You need to iterate through your objects and change the original_title to original_name or original_name become original-title.

Example

const movies = [
  { title: 'Dark Land' },
  { title: 'Dark Land' },
  { name: 'Dark Land' },
];

const changedKeys = movies.map((movie) => {
  const { title, ...otherProps } = movie;
  const newMovieStruct = { name: title, ...otherProps };
  return newMovieStruct;
});
console.log(changedKeys);
  • Related