Exploring deeply nested arrays in objects to locate matching elements

In my current array, there are multiple objects, each containing an array property. The array within each object holds different genres associated with a movie.

const films = [
    {
    name: 'Ant-Man and the Wasp',
    genre: ['Action' , 'Adventure' , 'Sci-Fi' , 'Comedy']
  },
  {
    name: 'Sorry to Bother You',
    genre: ['Comedy' , 'Fantasy']
  },
  {
    name: 'Jurassic World: Fallen Kingdom',
    genre: ['Action' , 'Adventure' , 'Sci-Fi'],
  },
  {
    name: 'Incredibles 2',
    genre: ['Action' , 'Crime' , 'Drama' , 'Thriller']
  },
  {
    name: 'Deadpool 2',
    genre: ['Action' , 'Adventure' , 'Comedy']
  }
];

My goal is to iterate through the objects in the array and identify matches based on genres. However, the code I'm currently using doesn't seem to be producing the expected results. Is there a better way to identify matches between objects based on their genres?

for (let i = 0; i < films.length; i++) {
  let film = films[i];
  let genres = film.genre;

  for (let j; j < genres.length; j++) {
    if (genres[j] == "Action") {
      console.log('Match');
    } else {
      console.log('No Match');
    }
  }
}

Answer №1

I'm proceeding on the belief that the presence of two distinct property names is intentional and not a mistake, with genre and dependencies.

Regardless, you can achieve it with a concise one-liner:

const films = [{name: 'Ant-Man and the Wasp',genre: ['Action' , 'Adventure' , 'Sci-Fi' , 'Comedy']},{name: 'Sorry to Bother You',genre: ['Comedy' , 'Fantasy']},{name: 'Jurassic World: Fallen Kingdom',dependencies: ['Action' , 'Adventure' , 'Sci-Fi'],},{name: 'Incredibles 2',dependencies: ['Action' , 'Crime' , 'Drama' , 'Thriller']},{name: 'Deadpool 2',dependencies: ['Action' , 'Adventure' , 'Comedy']}];

let actionflicks = films.filter(f => (f.genre || f.dependencies).includes( 'Action'))
console.log(actionflicks)

Regarding your code, it's a decent starting point, but it is currently throwing errors. It's advisable to check the console when troubleshooting issues. It will help identify the problem areas.

Answer №2

There are several errors in this script. The corrected version should look like this:

const movies = [
    {
    name: 'Ant-Man and the Wasp',
    genre: ['Action' , 'Adventure' , 'Sci-Fi' , 'Comedy']
  },
  {
    name: 'Sorry to Bother You',
    genre: ['Comedy' , 'Fantasy']
  },
  {
    name: 'Jurassic World: Fallen Kingdom',
    genre: ['Action' , 'Adventure' , 'Sci-Fi'],
  },
  {
    name: 'Incredibles 2',
    genre: ['Action' , 'Crime' , 'Drama' , 'Thriller']
  },
  {
    name: 'Deadpool 2',
    genre: ['Action' , 'Adventure' , 'Comedy']
  }
];

for (let i = 0; i < movies.length; i++) {
  let movie = movies[i];
  let genres = movie.genre;

  for (let j = 0; j < genres.length; j++) {
    if (genres[j] == "Action") {
      console.log('Match');
    } else {
      console.log('No Match');
    }
  }
}

As mentioned by Mark, some objects in the array have properties named "dependencies" that should be named "genre". Also, in the line "for (let j; j < genres.length; j++) {", j needs to be initialized with a value.

Answer №3

Make sure to check the condition before iterating through the genres

for (let i = 0; i < films.length; i++) {
  let film = films[i];
  let genres = film.genre;

  if (genres !== undefined){
  for (let j; j < genres.length; j++) {
    if (genres[j] === "Action") {
      console.log('Match');
    } else {
      console.log('No Match');
    }
  }
  }
}

Answer №4

When looking at other objects, it is important to note that the key is different. For the last 3 objects, the key is 'dependencies' instead of 'genre'. This means that while traversing through the last 3 objects, films[i].genre will be undefined, leading to an error at genres.length.

If you also wish to traverse through 'dependencies', you can use the following code:

for (let i = 0; i < films.length; i++) {
 let film = films[i];
 let genres = film.genre || film.dependencies; // check for 'genre' first, then 'dependencies'
 if (!genre) { continue; } // skip the loop if neither 'genre' nor 'dependencies' exist
 for (let j; j < genres.length; j++) {
  if (genres[j] == "Action") {
   console.log('Match');
  } else {
   console.log('No Match');
  }
 }
}

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

I am encountering a problem with the $invalid property in AngularJS

Hey there, I've got a coding dilemma involving three number inputs, which I will refer to as the first input, second input, and third input for clarity. Here's the setup: <div> <form name="formOpenMax"> <div clas ...

Tips for incorporating the camera from fbxloader into your three.js scene

I am currently utilizing fbxloader from three.js to incorporate a model into my scene. I have noticed that the most recent version of fbxloader.js (https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/FBXLoader.js) has the capability to read ...

Initiate navigation in AngularJS through routing

My AngularJS app has a reset link that I need to use to reset it... <a ng-click="resetApp()">reset</a> The button press is being handled in the main controller... $scope.resetApp = function(){ if(confirm("You will lose data...")){ ...

Is it possible to nest ng-repeat and access $first and $last properties simultaneously

Below is the form that I am currently working with, <tbody ng-repeat="attGroup in attributesGroups"> <tr> <td class="vcenter text-right"> &nbsp;&nbsp;<a href="javascript:" ng-click="!$last && up ...

Using async await in a React component causes a syntax error

Struggling with setting up a basic react app using hapi.js on the server-side, I am diving into the world of webpack and babel as a newcomer. Here's a glimpse at my React component App.jsx: import React from 'react'; export default class A ...

Discover an Effective Approach for Transmitting Form-Data as a JSON Object

Hey there! I'm encountering a bit of an issue with sending some data as a JSON object. The problem arises when trying to send images using FormData. It seems like I need to convert my form data into a single JSON object. Can anyone assist me with this ...

Request successful but receiving no response text and content length is zero

let req = new XMLHttpRequest(); req.addEventListener('load', function (data) { console.log(data) }, false); req.open("get", "/bar.txt", true); req.send(); Feeling a bit perplexed at the moment, I can't seem to figure out what's going ...

Angular Bootstrap Modal provides a sleek overlay for user input forms

Trying to access an angular form within scope for validation purposes. Initial Scenario Consider the following HTML: <body ng-controller='MyAwesomeController'> <form name="fooForm"> <textarea ng-model="reason" required= ...

What is the best way to show JSON array data in jQuery without using double quotes?

I have encountered an issue where I need to remove the double quotes from my json_encode output. To achieve this, I have used the following code: $json_string = json_encode($data); $json_string = str_replace('"','',$json_string); echo ...

Determine whether an object exists within another object and merge its value into the formatted object

When filling out a form, I have a formattedData object that holds a deep copy of the original data object. If a field in the form is changed, I must update the formatted data object with properties from the values object. To simulate this scenario, I crea ...

Tips for accessing form data that has been automatically uploaded in PHP

I've been trying to automatically post data using JavaScript and retrieve it in a PHP file. However, I am facing an issue where the PHP file is not able to retrieve the data. I have set up an automatic form that takes input from another form and send ...

The information was not displayed in the message exchange

I'm currently working on a project involving a google chrome extension where the content.js script sends a message to popup.js. I'm also attempting to take some text from content.js and display it in popup.js. Here is my entire code: Here's ...

Utilizing a single v-model for several elements

I am having an issue with a dropdown that is set to v-model="compose.Recipient". Based on the value of "compose.Recipient", I need another dropdown to appear as shown below: <div class="form-group" v-if="compose.Recipient==2" title="Select Class"> ...

An issue occurred when attempting to integrate Angular

Currently, I am in the process of learning AngularJS. To practice, I attempted a simple code snippet in an HTML file: <!DOCTYPE html> <html lang="en" ng-app=""> <head> <meta charset="utf-8"> &l ...

Utilizing server-side cookies in next.js and nest.js for efficient data storage

I have been working on a small application using Next.js and Nest.js. One of the functionalities I implemented is a /login call in my client, which expects an HttpOnly Cookie from the server in response. Upon receiving a successful response, the user shoul ...

Retrieve and update the most recent entry

Here is the schema I am working with: var BudgetInfoSchema = mongoose.Schema({ user_email: { type: String, required: true }, user_budget: { type: Number, required: true }, platforms_budget: { type: [{ platform_id: { type: String, required ...

JavaScript Async Ordering

I have a specific question regarding asynchronous operations in Javascript. I am currently building a Node.js API to interact with an OrientDB database, using the Node-orient package for basic connectivity functions. Some of these functions are as follows: ...

Angular 2 - synchronizing timer for all users

I have developed a timer that needs to function consistently for all users at the same time. To achieve this, I stored the start_time (timestamp when the timer begins) in my database and implemented the following code snippet to calculate the remaining ti ...

How to Transfer Information Between Two React Components

I recently started learning React and I'm not sure how to approach this task. Basically, I have a list of cars and when the user clicks on each car, it should display detailed information about that specific car in a full-page slide. This is my curr ...

Developing dynamic-sized tuples in TypeScript

Recently, I was attempting to develop a zipper for arrays. For instance, if the user inputs 3 arrays with sizes of 3, 5, and 12, the output array of tuples would be the size of the largest array. The output consists of tuples containing elements at a speci ...