Tips on selecting specific data from a nested JSON array based on conditions and fetching just one value from the initial filtered result with Javascript (designed for Google Sheets)

Utilizing the TMDB API for retrieving movie data and integrating it into a Google Sheet. The original Google Sheet was revamped from Reddit user 6745408's "MediaSheet 3.0". This sheet incorporates a Javascript-based script. By following the patterns/code used in the initial script, I managed to extract values for keys that were not present originally. However, I am faced with a challenge:

There exist multiple arrays nested within the "results" key. Each array under "result" represents a video associated with the movie title. My goal is to fetch the URL ending ("key") of a particular video into the Google Sheet. Specifically, I aim to filter the "results" array to include videos with values ("site": "YouTube") and either ("type": "trailer) or ("type": "teaser"), selecting the first result meeting these criteria and returning its corresponding "key".

The JSON data from the TMDB API that requires parsing:

{
  "id": 290098,
  "results": [
    {
      "iso_639_1": "en",
      "iso_3166_1": "US",
      "name": "In the Projection Booth - Park Chan-wook, director of The Handmaiden (contains spoilers)",
      "key": "P8g8QJk96M4",
      "site": "YouTube",
      "size": 1080,
      "type": "Featurette",
      "official": true,
      "published_at": "2017-04-14T08:30:01.000Z",
      "id": "65be6283902012012fc9a5a7"
    },
    ...
  ]
}

The Google Sheets App Script code currently being worked on:

function TMDBmovietrailer123(rows) {
  var tmdbKey = PropertiesService.getScriptProperties().getProperty('tmdbkey');
  const requests = rows.map(id => {
    return {
      url: `https://api.themoviedb.org/3/movie/${id}/videos?api_key=${tmdbKey}`,
      muteHttpExceptions: true
    }
  })
  const responses = UrlFetchApp.fetchAll(requests)
  return responses.map(request => {
    try {
      const data = JSON.parse(request.getContentText());
      const id = data.id

      return [id]
    } catch (err) {
      return ['']
    }
  })
}

Answer №1

The results variable holds an Array of anonymous objects. While you can still apply the filter method to it, in your scenario, using the find method of Array might be more suitable. The main difference is that filter continues processing the entire array even after finding a matching item, whereas find stops as soon as it finds the first matching element.

If we consider the object containing both id and results as a response, you can handle it like this (with simplified response data):

const response = {
  "id": 290098,
  "results": [
    {
      "key": "P8g8QJk96M4",
      "site": "YouTube",
      "type": "Featurette"
    },
    {
      "key": "xX7HsdfIYGw",
      "site": "YouTube",
      "type": "Teaser"
    },
    {
      "key": "wYsdzNIcJNc",
      "site": "YouTube",
      "type": "Trailer"
    },
    {
      "key": "5bOWrDriBno",
      "site": "YouTube",
      "type": "Clip"
    }
  ]
}


const trailer = response.results.find((o) => (o?.site === 'YouTube') && (o?.type === 'Trailer' || o?.type === 'Teaser'))

console.log(trailer?.key || 'not found')

You can further enhance this by checking if a specific property exists in an object using

typeof o.<property> !== 'undefined' && o.<property> === 'value'
.

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

How to extract a variable from a mongoose find method in a Node.js application

Within my Node.js program, I utilize my Mongoose database to query for a specific value in a collection, of which there is only one value present. var myValueX; myCollection.find(function(err, post) { if (err) { console.log('Error ...

Securing a JWT token post login

I am new to NodeJS and despite trying numerous solutions, I am facing a challenge. My project involves NodeJS, MongoDB, Express, and Vanilla JS rendered through Pug with an MVC structure. Issue Current Status: I can successfully log in a user and recei ...

What are the steps to modify or remove a node in react-sortable-tree?

I am currently working on implementing a drag and drop tree view using react-sortable-tree. Along with that, I also need to incorporate CRUD operations within the tree view. So far, I have been successful in adding, editing, and deleting nodes within the p ...

The Jquery script is ineffective for newly added elements

After creating an Ajax Form that functions well, I noticed that when the result of the form is another form, my script does not work for the new form generated. Is there a way to make the new form function like the old one? $(document).ready(function() ...

Employ a pivot table to visually display an array of object data

I am attempting to utilize a pivot table to organize the data provided below: $.pivotUtilities.tipsData=[ {status:"open",year:2014,value:100.00}, {status:"open",year:2015,value:200.00}, {status:"open",year:2016,va ...

Looping through a JSON array and encoding it using the `

I am looking to retrieve data from the database using AJAX and populate a 'select' tag with that data. Each name should be displayed in its own 'option'. Here is the code snippet: Index.php: <label>Select:</label> <sel ...

Scripting issues detected in Safari and Microsoft Edge browsers

I recently finished developing an AngularJs Application that works flawlessly on Google Chrome and Mozilla Firefox. However, upon testing it on Safari and IE-11, I encountered errors in the console. One particular piece of code that causes issues is used ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...

Effortlessly Concealing Numerous Elements with a Single Click in Pure JavaScript

I have successfully created an HTML accordion, but I am facing an issue. I want to implement a functionality where clicking on one accordion button will expand its content while hiding all other accordion contents. For example, if I click on accordion one ...

This asynchronous function will provide a response of "undefined"

Having a challenge with an async function that should return a geocode value: async function getLocationCoordinates(place){ //var str; return googleMapsClient.geocode({ address: place }).asPromise() .then((response) => { response.json.results[0].ge ...

jQuery fails to operate on products loaded through AJAX requests

Upon opening the page, jQuery functions correctly. However, when a product is loaded or changed via AJAX, jQuery stops working. I am currently using jquery-1.7.1.min.js $(document).ready(function () { $screensize = $(window).width(); if ($screensi ...

html carousel not updating in popover

I've been attempting to create a popover with a bootstrap carousel, where the carousel items are dynamically generated and appended from a script. Despite my efforts, I have successfully displayed the carousel but struggle to append the items. I' ...

Mastering the use of npm and sails to create HTML-PDF files effortlessly

UPDATE: I am simplifying my question and will address any other concerns in separate posts if necessary. The initial post was too lengthy, hoping for a straightforward guide on utilizing sails to its fullest potential. Apologies. To begin with, my knowled ...

The caching of AJAX POST requests is a common occurrence

In my web application, I have implemented a functionality where a POST request is sent to the URL /navigate.php and it works correctly. However, the challenge arises when the application needs to function offline. In such cases, I aim to display a notifica ...

Transferring information between a pair of input fields using ngModel

There are two input fields named input1 and input2. An event has been created where anything typed in input1 is displayed in input2. However, if something is manually changed or typed into input2, the event should not trigger. I think I may need to use a ...

Solving Cross-Origin Resource Sharing problem in an Express JS application

I have encountered a CORS error while using this code, despite having applied the necessary cross-origin headers. I am seeking guidance on how to resolve this issue. var express = require('express'); var bodyParser = require('body-parser&ap ...

Displaying the initial element in an NgFor loop in Angular 2

Whenever I click on the "Add row" button, I dynamically generate a row of inputs and dropdowns. Upon clicking another button, the complete data is submitted and displayed in console.log as an array of objects, with each object representing a single row. C ...

Is it possible that activating the alert() function within a Node.js script could cause the server to freeze completely?

Given that Node.js operates on a single thread, is there a risk of freezing the entire server by calling functions like alert(), which typically wait for user input? Does Node.js have mechanisms in place to prevent such issues? ...

Learn how to effortlessly download a file from Amazon S3 using Angular and ng-click technology

When attempting to download a file from my Amazon S3 bucket using Angular's ng-click, I am receiving a blank file instead of the expected content. HTML <div class="details-field"> RC Book <font class="digit" >({{rcCount}})</font> ...

Flutter Error: The function 'jsonEncode' does not exist in this context

I am struggling to send a put request to an API in Flutter using the function below: Future<http.Response> login(String username, String password) { return http.put( Uri.parse('apiurl'), headers: <String, String>{ ...