In Vue.js2, you can easily compare two arrays of objects that have the same values and then make changes or add properties from one array to the other

I am working with an array of objects fetched from an API (), which is linked to a variable that serves as the v-model for an input. Whenever the variable changes, so does the array through a function that triggers the API call on @keyup. The structure of this array looks like this:

(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, __ob__: we]
0:
backdrop_path: "/pLG4ihU1d2XkQbASQDjsFu9U7d9.jpg"
first_air_date: "2021-03-24"
genre_ids: Array(3)
0: 18
1: 80
2: 9648
length: 3
__ob__: we {value: Array(3), dep: ce, vmCount: 0}
__proto__: Array
id: 120168
media_type: "tv"
name: "Che fine ha fatto Sara?"
origin_country: Array(1)
original_language: "es"
original_name: "¿Quién mató a Sara?"
overview: "Determinato a vendicarsi e a provare di essere stato incastrato per l'omicidio della sorella, Álex cerca di scoprire molto più del vero colpevole del crimine."
popularity: 529.698
poster_path: "/jnit57q25N5VvVrK4pj4Uj8BLe7.jpg"
vote_average: 7.8
vote_count: 430

Although this array provides valuable information about movies and TV series, it lacks genre names and only includes their corresponding IDs. To address this issue, I have accessed another API that offers a list of genres structured like this:

(19) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
id: 28
name: "Azione"
__proto__: Object
1:
id: 12
name: "Avventura"
__proto__: Object
2: {id: 16, name: "Animazione"}
3: {id: 35, name: "Commedia"}
4: {id: 80, name: "Crime"}
5: {id: 99, name: "Documentario"}
6: {id: 18, name: "Dramma"}
7: {id: 10751, name: "Famiglia"}
8: {id: 14, name: "Fantasy"}
9: {id: 36, name: "Storia"}
10: {id: 27, name: "Horror"}
11: {id: 10402, name: "Musica"}
12: {id: 9648, name: "Mistero"}
13: {id: 10749, name: "Romance"}
14: {id: 878, name: "Fantascienza"}
15: {id: 10770, name: "televisione film"}
16: {id: 53, name: "Thriller"}
17: {id: 10752, name: "Guerra"}
18: {id: 37, name: "Western"}
length: 19
__proto__: Array(0)

In this new array, each object contains the same genre IDs found in the initial array under the genre-ids sub-array. My approach involves comparing both arrays, identifying matching genre IDs, and adding corresponding genre names to the objects in the first array. This will allow me to display the genre names in HTML. I am currently using Vue 2.

Answer №1

Check out this concise solution for inspiration:

const films = [{genre_ids: [1,2]}, {genre_ids: [2]}, {genre_ids: [1,3]}];
const categories = [{id: 1, name: "category1"}, {id: 2, name: "category2"}, {id: 3, name: "category3"}];
const filmsWithCategories = films.map(film => ({
    ...film,
    categories: categories.filter(({ id }) => film.genre_ids.includes(id))
}));

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

Calculate the total price from a combination of HTML and JavaScript options without altering the values

I'm currently facing an issue in my form where the final price needs to be updated when a different option is selected. I've searched extensively for the problem without success. I've used similar code before, just with different variables a ...

Encountering difficulty with installing node_modules on Express js

Encountered an error while attempting to install node_modules from the package.json file. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Assign a unique ID to every object in the array following submission

After receiving input from an input and text area, I am attempting to assign a unique ID property to each object in an array. When I log the array after adding more entries, it appears as follows: [{"title":"hello","text":&quo ...

What could be causing the issue with ng-include not functioning properly?

Issue with ng-include Organized Directory Structure : ssh_project --public ----templates ------header.html ------footer.html ----views ------index.html Here is the content of my index.html file <body> <h1>Hello</h1> <div ng ...

Adjusting the height of a textarea within a table

My textarea's height is supposed to be 500%, but it's not changing. I suspect that being inside a table might have something to do with the issue, but I'm unsure of what needs to be adjusted to set the height correctly. Surprisingly, the wid ...

The PDF structure in vue3-pdf is not valid and may cause errors

This error is occurring on almost every file, except for one that works fine. The console also displays the following warning: Warning: Indexing all PDF objects. Object { message: "Invalid PDF structure.", name: "InvalidPDFException", ...

Is it possible to generate objects dynamically as the program is running?

Looking at the code snippet below, I currently have an array containing two JSON objects. However, if I need to create 20 objects, is there a more efficient way than manually writing each object in the array? Furthermore, is it possible to generate these o ...

How can I resolve the issue of Nuxt not loading an inlined SVG as a Vue component in Firefox?

I encountered an issue when trying to use SVG icons in a .vue file as a component. The icons work fine in Chrome, but I'm getting errors in Firefox and the icons are not rendering properly. The error message points to a specific icon, so I need some g ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

Struggling to insert a JavaScript variable into a MySQL database table using PHP and AJAX

As a newcomer to these technologies, I've been struggling all day with what I expected to be a simple task. My goal is to pass a parameter from a JS function to my PHP code using AJAX and then insert that parameter into my database. Here's the J ...

Attempting to scroll through a webpage and extract data using Python and Selenium in a continuous manner

Recently, I posed a question (you can find it here: Python Web Scraping (Beautiful Soup, Selenium and PhantomJS): Only scraping part of full page) that shed light on an issue I encountered while attempting to scrape all the data from a webpage that updates ...

Extracting information from a hyperlink without the need to actually click on it

Hello, I have recently started learning JavaScript and I am looking to accomplish a specific task. Currently, I am navigating on A.com/. Within the content of A.com/, there is a link labeled as A.com/B. Upon clicking on the link A.com/B, I can see ...

Troubleshooting Checkbox Validation Problem in Vue JS

Deactivating Vue js Validation In the following piece of code, I am trying to disable a checkbox when item.status == "active". I attempted to use :disbale="item.status='active'"" in my checkbox. With this code snippet, the ...

The attempt to remove the ajax-loaded page while preserving the original div is proving to be

I have a function that is triggered when a link is clicked. This function uses ajax to load a new page over a div. <pre><code> function displayContent(id) { loadPage_signup = "register.php"; loadPage_info = "userinfo.php"; $.aj ...

Press the Text and Alter Text with React

I'm having an issue with the onClick event using React hooks. My goal is to have the text change to a different one when the user clicks, and then revert back to the original text on another click. For example, clicking "Change First" should switch it ...

List of characteristics belonging to objects contained within an array

Consider the following array of objects: data = [{x: 1, y: 2, z: 3}, {x: 4, y: 5, z: 6}, {x: 7, y: 8, z: 9}] Is there a way to extract only the x elements from these objects and create an array out of them? For example: x = [1, 4, 7] Can this be achiev ...

Converting and downloading CSV to XLSX directly from the front end using TypeScript and React

After successfully converting a JSON response to CSV format for download using the function below, I am now looking to achieve the same functionality but with xlsx files on the front end. The current function works well for CSV files and handles Japanese ...

Every time I attempt to build a React application, I encounter the same error message. I even checked the log file, but it keeps showing the proxy error

An error occurred in the command prompt while installing packages. This process may take a few minutes. Installing react, react-dom, and react-scripts with cra-template... Error: ERR_SOCKET_TIMEOUT The network encountered a socket timeout while trying to ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

The Vuex state fails to update unless the page is refreshed

In the process of developing a single page application, I have implemented functionality that displays different pages based on whether users are logged in or not. The login feature is functioning as expected, with an authorization token being stored in Lo ...