Sort through nested objects

Trying to filter an array of movies by genre using a function but encountering a TypeError:

TypeError: movie.genres.some is not a function.
(in 'movie.genres.some(function(item){return item.name === genre;})',
'movie.genres.some' is undefined) `
Movie class =>  
  title: string,
  ...,
  genres: Genre[]

Genre class => 
  id: number,
  name: string
FilterMovies = (genre: string) => {
  let fmovies: Movie[] = this.state.movies.filter((movie) => {
    let data = movie.genres.some((item) => item.name === genre);
    return data;
  });

Seeking guidance on whether the functions are being used correctly, any help would be greatly appreciated!

edit: example of movie object can be viewed here: https://i.sstatic.net/C9q7o.png

Answer №1

Based on the error message you've received, it appears that the genres property within the Movie class is not functioning as an array of Genre, since all arrays should have a some property (unless you intentionally removed it). It seems more likely that the genres property is mistakenly set to be just a single Genre object.

Answer №2

After considering some suggestions from the comments, I managed to resolve the issue using the steps below:

  • Discovered that my object was not an array, so I utilized Object.values to access the values within the collections
  • Ensured to verify that every movie contained a genre object that was neither null nor undefined

While it may not be flawless yet, the current solution is operational. Here's the updated code:

FilterMovies = (genre: string) => {

let filteredMovies: Movie[] = this.state.movies.filter((movie) => {
  let genreObj;
  if (movie.genres != null || typeof movie.genres !== "undefined") {
    genreObj = Object.values(movie.genres);
  } else {
    return null;
  }
  
  let genreNames: string[] = [];

  if (genreObj != null || typeof genreObj !== "undefined") {
    genreObj?.forEach((gen) => {
        genreNames.push(gen.name);
      });
  } else {
    return null;
  }

  let result = genreNames.some((item) => item === genre);
  return result;
});

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

Generating CSV headers for all nested objects in JavaScript

Utilizing the "react-json-to-csv" library to convert my JSON data into a CSV file has presented an issue with nested objects. The CSV export header is breaking, displaying alternate data because of these nested objects. Here's an example of my JSON da ...

How can I encode and decode a base64 string using AngularJS1 and TypeScript?

I am currently working with Angular1 using TypeScript and I have a question that needs some clarification. Within the environment that I am operating in, is there a method available to encode and decode a string in base64? Despite conducting extensive re ...

Saving the object array to a file

Encountering an issue while trying to write an object array into a file in JAVA specifically with integer values. Collections.shuffle(list); r = (Object[])list.toArray(); Attempted to write the object array "r" to a file using the following code. fos = ...

Alert: There are unresolved parameters for Storage in the file located at PATH/node_modules/@ionic/storage/es2015/storage.d.ts

Important Notice: Caution: Cannot resolve all parameters for Storage in /Users/zzm/Desktop/minan/node_modules/@ionic/storage/es2015/storage.d.ts: (?). This will become an error in Angular v5.x I have followed the instructions in this answer but the ...

The type 'Observable<boolean>' cannot be assigned to type 'Observable<UserRegistration>'

function completeRegistration(email: string, password: string, firstName: string, lastName: string, location: string): Observable<UserDetails> { let body = JSON.stringify({ email, password, firstName, lastName,location }); let headers = new H ...

Using Selenium to trigger the display of tooltips programmatically in Highcharts

I am faced with a situation where I need to automate some actions using selenium on a third-party website, which likely means I cannot utilize the highcharts API. Upon loading the third-party website, there is no tooltip element present in the HTML body. ...

The website experiences a sudden crash shortly after launching, displaying the error message "EADDRINUSE" for port 80

PROBLEM I have a react-based website running on a node-express server. My backend server is working fine on port 3000, but the website on port 80 keeps crashing. When I use pm2 to start my website (https://www.edvicer.com) with the command pm2 start serv ...

The successful execution of one promise determines the outcome of the $q.all promise

I am currently dealing with a situation where I have three nested promises that I need to refactor into a single $q.all call. The current structure of the code looks like this: ds.saveData(data).then(function (result1){ someOtherVar = result1.Id; ...

How does the AngularJS Dependency Injection system determine the names of the arguments it needs to inject?

Here is an example directly from the official website: function PhoneListCtrl ($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.orderProp = 'age'; } The $s ...

Creating a row of aligned card components in React

Recently, I began learning React and successfully created a card component using Material UI. However, this time around, I'm attempting to create it using axios and map() methods. I expected the cards to be displayed in the same row horizontally, not ...

Tips for sending user IDs through an Angular 8 interceptor

Alright, In my Angular application that is using version 8, I have an HttpMaintenanceInterceptor configured without the use of cookies. Instead, I have a getAccessToken method within the authService as shown below: getAccessToken(): string { return ...

Exploring the possibilities of using AngularJS for AJAX functionality in a Ruby On Rails

I recently started learning AngularJS and Rails, and I attempted to develop a Rails application incorporating AngularJS. Currently, I am looking to make a POST request to send data and insert it into the database. In the Activity Controller: def create ...

How can I extract and display a particular attribute from an object in a list retrieved through AJAX?

I am currently working on an AJAX call that retrieves a list of objects in JSON format from a database. These objects are then used in an autocomplete text input. However, my challenge is to display only the NAME attribute of each object in the list. $(fu ...

"Encountered an error message: Unable to retrieve property 'getCapabilities' due to a TypeError

Everything was going smoothly with my tests until I encountered an issue when the browser.getCapabilities(); method was called in the OnComplete function, resulting in an error. //The HTMLReport is triggered once all tests are completed onComplete: f ...

Transferring user inputs to the server through jQuery-AJAX

I've encountered some issues when trying to send form data inputs to the server. Despite alerting each form input, I keep getting empty alerts. Here's my code snippet: With my current code, it only alerts 0. However, posting normally seems to wor ...

What is the process for converting an Excel file into a 2D array during deserialization

Currently, I'm working with an Excel spreadsheet in which all the fields are strings. My goal is to extract and de-serialize all the data from this file into a 2D array or matrix. Does anyone have any suggestions on how I can begin this process? ...

Having trouble retrieving the toDataURL data from a dynamically loaded image source on the canvas

Currently, I am working on a project that involves a ul containing li elements with images sourced locally from the "/images" folder in the main directory. <section class="main"> <ul id="st-stack" class="st-stack-raw"> ...

Having trouble locating a method in $scope following angular $compile

Apologies for the simple question, I am a beginner in AngularJS and front-end development. I am attempting to create a modal using bootbox as shown below: In Service: function _modalData(){ let element = "<div onclick=\"saveSelecti ...

Prevent repeating the same table header multiple times when generated dynamically with jQuery

I have an array called groups which contains name and regid. I want to display the name key as the column header of a table. To achieve this, I implemented the following code: var Name = v.name; var regId = v.regid; var rowStr = '<th d ...

Once an email address is entered, kindly instruct the driver to press the tab key twice for navigation

Adding a user to a website involves entering an email address first, which is then checked against the server's list of users. However, the issue arises when the email validation doesn't occur until clicking outside the input box or pressing tab ...