Retrieve Javascript data from JSON only if the specified parameter is set to true

I'm currently utilizing the TMDB API for fetching movie details and I want to extract the trailer from YouTube. If my JSON data appears as follows...

{
  id: 568124,
  results: [
    {
      iso_639_1: "en",
      iso_3166_1: "US",
      name: "What Else Can I Do?",
      key: "PnJY20UCH9c",
      site: "YouTube",
      size: 1080,
      type: "Clip",
      official: true,
      published_at: "2021-12-13T21:54:56.000Z",
      id: "61b7d50b037264001cadc6e1",
    },
    {
      iso_639_1: "en",
      iso_3166_1: "US",
      name: "Official Trailer",
      key: "CaimKeDcudo",
      site: "YouTube",
      size: 1080,
      type: "Trailer",
      official: true,
      published_at: "2021-09-29T13:00:05.000Z",
      id: "615570dd07e281008dac4a0e",
    },
  ],
};

How do I specifically fetch the KEY from the video identified by the NAME 'OFFICIAL TRAILER'. Currently, I can retrieve the first result ([0]) from the list using the code below...

let movieTrailerUrl = data.videos.results[0].key;
document.getElementById('movie-trailer').innerHTML +=
`<div class="video-responsive"><iframe width="560" height="315" src="https://www.youtube.com/embed/${movieTrailerUrl}" title="${movieTitle}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>`;

However, I need to ensure that the video selected from the JSON data is the one labeled 'OFFICIAL TRAILER'. Is there a way to extract the key only when the 'name' matches 'Official Trailer'?

Answer №1

Utilize the Array.find method to locate the node that matches its name. For instance, if you are searching for an item in the array with the name exactly as "Official Trailer", use the name and title of that matching node to generate the video link.

const apiResponse = {
  id: 568124,
  results: [
    {
      iso_639_1: "en",
      iso_3166_1: "US",
      name: "What Else Can I Do?",
      key: "PnJY20UCH9c",
      site: "YouTube",
      size: 1080,
      type: "Clip",
      official: true,
      published_at: "2021-12-13T21:54:56.000Z",
      id: "61b7d50b037264001cadc6e1",
    },
    {
      iso_639_1: "en",
      iso_3166_1: "US",
      name: "Official Trailer",
      key: "CaimKeDcudo",
      site: "YouTube",
      size: 1080,
      type: "Trailer",
      official: true,
      published_at: "2021-09-29T13:00:05.000Z",
      id: "615570dd07e281008dac4a0e",
    },
  ],
};

const movieTrailer = apiResponse.results.find(node => node.name.toUpperCase() === 'OFFICIAL TRAILER')
const movieTrailerUrl = movieTrailer.key;
const movieTitle = movieTrailer.name; // Identify the correct node
document.getElementById('movie-trailer').innerHTML +=
  `<div class="video-responsive"><iframe width="560" height="315" src="https://www.youtube.com/embed/${movieTrailerUrl}" title="${movieTitle}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>`;
<div id="movie-trailer"></div>

Answer №2

It seems like you're looking for a single key that matches the name "official trailer."

// Here is the data with some added variables for demonstration
const movieData = {
  id: 568124,
  results: [
    {
      iso_639_1: "en",
      iso_3166_1: "US",
      name: "What Else Can I Do?",
      key: "PnJY20UCH9c",
      site: "YouTube",
      size: 1080,
      type: "Clip",
      official: true,
      published_at: "2021-12-13T21:54:56.000Z",
      id: "61b7d50b037264001cadc6e1",
    },
    {
      iso_639_1: "en",
      iso_3166_1: "US",
      name: "Official Trailer",
      key: "CaimKeDcudo",
      site: "YouTube",
      size: 1080,
      type: "Trailer",
      official: true,
      published_at: "2021-09-29T13:00:05.000Z",
      id: "615570dd07e281008dac4a0e",
    },
  ],
};

const {results } = movieData;
console.log(results);

let matchingKey;
results.forEach((element) => {
    if(element.name.includes("Official Trailer")) {
    matchingKey = element.key;
  }
});
console.log(matchingKey);

Answer №3

let selectedTrailer = data.videos.results.find((trailer) => trailer.name === 'Official Trailer');

// Conditional statement is necessary because `.find` can return undefined if the value is not found
if (selectedTrailer) {
    console.log(selectedTrailer.key);
}

It would also be a good idea to convert all values to lowercase, for example:

trailer.name.toLowerCase() === 'Official Trailer'.toLowerCase()

Answer №5

It seems like you are looking to extract the "official trailer" object from an array of objects

var data = {
  id: 568124,
  results: [
    {
      iso_639_1: "en",
      iso_3166_1: "US",
      name: "What Else Can I Do?",
      key: "PnJY20UCH9c",
      site: "YouTube",
      size: 1080,
      type: "Clip",
      official: true,
      published_at: "2021-12-13T21:54:56.000Z",
      id: "61b7d50b037264001cadc6e1",
    },
    {
      iso_639_1: "en",
      iso_3166_1: "US",
      name: "Official Trailer",
      key: "CaimKeDcudo",
      site: "YouTube",
      size: 1080,
      type: "Trailer",
      official: true,
      published_at: "2021-09-29T13:00:05.000Z",
      id: "615570dd07e281008dac4a0e",
    },
  ],
};

console.log(data.results.find(item => item.name === "Official Trailer"))
console.log(data.results.find(item => item.name === "Official Trailer").key)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with iframe's size not displaying correctly

<body> <script> document.write("<iframe id='theframe' src='http://www.website.com?testvr=" + testvr + " height='900' width='500'></iframe>"); </script> </body> The iframe is added, but ...

Navigating through the complexities of scoping in JavaScript when integrating Node.js

Currently, I am working on an express.js application without using mongoose. My goal is to create a function that can handle calls to MongoDB, pass parameters to it, and retrieve data from the database. However, I have encountered a problem with the foll ...

Converting JSON data retrieved from a webpage into a List of objects using C#

Currently, I'm encountering issues while trying to read a JSON file. Here is the content of the file: { "players": [ { "Player": "124", "Last Name": "DE SANCTIS", "Position": "P", "Team": "ROM" }, { "Player ...

What is the best way to extract characters from a jsonArray of Characters and save them into an ArrayList?

In my JSON file, I have the following JSON String: {"Q":[0,1,2,3],"q_0":0,"F":[3],"delta":[[0,1],[0,2],[3,2],[0,1]],"segma":[0,1]} I need to extract and store the 'segma' array as an ArrayList of Characters. static ArrayList<Long> Q; ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

The type check for the "list" prop failed while passing a JSON array. The expected type was an Array, but a String was received instead

I am encountering an issue with a json object, named jsonObject, that includes an array labeled tracks. I have been using this.jsonObject.tracks as an array in my methods and template (with v-for) without any issues in Vue. However, I am facing a problem w ...

Using a variable value as a regular expression pattern: A beginner's guide

I'm at my wit's end - I can't figure out where I'm going wrong. I've been attempting to replace all instances of '8969' but I keep getting the original string (regardless of whether tmp is a string or an integer). Perhaps ...

Discovering the depths of imagery on Android Q

Android Q introduced a new feature that allows users to retrieve depth maps from images. With the release of Android Q, cameras are now able to save depth data for images in a separate file using the Dynamic Depth Format (DDF) schema. This new format al ...

prioritizing the loading of the header in an Angular application before proceeding to load the main content

My website has a basic layout shown below: |-------------------| | HEADER | |___________________| |------||-----------| | side || Main | | bar || Content | | || | |------||------------ For routing and states, I am using ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

Create a JSON format using information extracted from a table

I have a list of characters like: a b c d e f ..and so on until Z Now, I need to convert this into JSON format and I'm feeling quite confused about how to do it. Should it look like this? {"rec":{"character":"a"}, "rec":{"character":"b"}} ...

Clicking a button in Angular JS to refresh a specific ID element

Just diving into AngularJS for my mobile web app development. I have different id divs for each view, as that's how AngularJS operates with one HTML page. My goal is to use specific javascript for each id page, as they need to retrieve JSON data objec ...

Unbounded AngularJS 1.x looping of Ag-grid's server-side row model for retrieving infinite rows

I am obtaining a set of rows from the server, along with the lastRowIndex (which is currently at -1, indicating that there are more records available than what is being displayed). The column definition has been created and I can see the column headers in ...

Error encountered when simulating the effect of calling 'insertPlayerData' function: ReferenceError - currentUserId has not been defined

PlayerList = new Mongo.Collection('players'); UerAccounts = new Mongo.Collection('user'); if(Meteor.isClient){ Template.leaderboard.helpers({ 'player':function(){ var currentUserId = Meteor.userId(); return Play ...

Iterate through every object in a JSON request using either jQuery or JavaScript

Admittedly, I'm fairly new to json/jQuery and JavaScript, so please bear with me if I make any obvious mistakes. Despite looking at similar questions, none of the solutions seemed to work for me. My goal is to retrieve the "image.full" property for e ...

The Android list is populated with just the final element

The issue arises after creating a list adapter following the parsing of a JSON file. Despite having correct content, the list only displays identical elements (the last element). What could be causing this problem? MainActivity: CatalogAdapter catAdapter ...

Communication between a directive controller and a service via an HTTP call

I'm currently developing an Angular directive that loads a Highchart.js area graph by passing some variables to it. Here's how I am using the directive: <andamento-fondo-area-chart color="#3FAE2A" url="../data.json"></andamento-fondo-a ...

Navigate through input fields while they are hidden from view

Picture this scenario: <div> <input tabindex="1"> </div> <div style="display:none"> <input tabindex="2"> </div> <div> <input tabindex="3"> </div> As I attempt to tab through these input f ...

Tips on invoking a class method within lodash debounce function

Help needed: Issue with TypeError - Expected a function at debounce when calling a class method in the lodash debounce class Foo { bar() { console.log('bar'); } } const foo = new Foo(); _.debounce = debounce(foo.bar(), 300); ...