I have an array of Youtube videos, and I want to know if they are contained in a particular playlist. I have this code:
var targetPlaylistId = "some_playlist_id";
var targetPlaylist = YouTube.Playlists.list("snippet", {id: targetPlaylistId});
var targetPlaylistTitle = targetPlaylist.items[0].snippet.title
var targetVideos = YouTube.PlaylistItems.list("snippet", {playlistId: targetPlaylistId, maxResults: 50});
for (var i = 0; i < sourceVideos.length; i++) {
var sourceVideoId = sourceVideos[i].snippet.resourceId.videoId;
var sourceVideoTitle = sourceVideos[i].snippet.title
var isAlreadyAdded = false;
for (var j = 0; j < targetVideos.items.length; j++) {
var targetVideoId = targetVideos.items[j].snippet.resourceId.videoId;
if (sourceVideoId == targetVideoId) {
isAlreadyAdded = true;
break;
}
}
if (!isAlreadyAdded) {
var resource = {
snippet: {
playlistId: targetPlaylistId,
resourceId: {
kind: "youtube#video",
videoId: sourceVideoId
}
}
};
YouTube.PlaylistItems.insert(resource, "snippet");
Logger.log("Added video " + sourceVideoTitle + " with ID " + sourceVideoId + " to playlist " + targetPlaylistTitle);
}
}
This works, but I have to loop over every video in targetPlayList for each one of the sourceVideos, which I don’t want to do if targetPlaylist is long.
Is there a way to ask Youtube "is video X already in playlist Y?"
>Solution :
Yep! There is a way to check if a video is in a playlist without looping through the entire playlist. You can use the PlaylistItems.list method to retrieve a list of videos in the playlist, and then use the videoId parameter to filter the results to only include the video you are looking for. If the video is in the playlist, the resulting list will contain one item with the video’s metadata. If the video is not in the playlist, the resulting list will be empty.
Here is an example code snippet:
var targetPlaylistId = "some_playlist_id";
var videoId = "some_video_id";
// You can get this video id by looping through your array of video ids
var existingItems = YouTube.PlaylistItems.list("id", {playlistId: targetPlaylistId, videoId: videoId});
if (existingItems.items.length > 0) {
// The video is already in the playlist
} else {
// The video is not in the playlist
}