Using Vue.js to iterate over a list of items and accessing specific array objects by their unique identifier

My JSON array of objects has the following structure:

https://i.sstatic.net/1IUVE.png

When generating a <ul>, I need to fetch an ID from an API for each <li>:

<ul>
  <li v-for="genre in movie.genre_ids">
    {{ genre }} // 19
  </li>
</ul>

However, instead of displaying the number, I want to show the name of the genre associated with that ID.

How can I achieve this in my code?

Answer №1

Transform your genres array into an object with the IDs as keys:

computed: {
  genresFormatted() {
    const genres = {};
    this.genres.forEach(genre => {
      genres[genre.id] = genre.name;
    });
    return genres;
  }
}

Now, accessing the name property when iterating becomes much simpler:

<li v-for="id in movie.genre_ids" :key="id">
  {{ genresFormatted[id] }}
</li>

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

using vuejs to pass a function as a prop

As I work on creating a foundational "TableComponent," incorporating selectable rows and more, I am faced with the requirement for this TableComponent to accept a prop named "buttons." These buttons are expected to be in the form of an array of objects ...

Is there a way to differentiate between a browser application running on a local development server and an online staging server?

Is there a way to conditionally call a component only on the staging server and not on the local machine in Vue.js? <save-drafts-timer v-if="!environment === 'development'" /> ... data () { return { environment ...

Vue no longer updates when the selected option is changed

Currently, I am working on an app for a class project and have encountered a problem involving fetching the value of a user-selected option instead of the default one. Below is the select element I am utilizing: <select v-model="selectedType" ...

Encountering errors with passport-google-oauth20: InternalOAuthError arises when fetching user profile fails and attempting to set headers after they have already been sent to the client

When using passport strategies for various social media logins, I encountered the following two errors: InternalOAuthError: Failed to fetch user profile Cannot set headers after they are sent to the client I suspect that I may have returned a callback or ...

inconsistent firing of mousedown events

On my webpage, I am using the following JavaScript code: $("#attach-body").mousedown(function (event) { //alert(event.button); switch (event.button) { case 2: event.preventDefault(); event.stopPropagation(); break; default: ...

Module cannot be resolved within react-viro

Having some issues running this application and receiving an error message. View the app code on GitHub here: https://github.com/vnovick/pile-blocks-ar I have followed the asset import instructions outlined here: . Despite following the steps correctly, I ...

What's causing Angular to not display my CSS properly?

I am encountering an issue with the angular2-seed application. It seems unable to render my css when I place it in the index.html. index.html <!DOCTYPE html> <html lang="en"> <head> <base href="<%= APP_BASE %>"> < ...

Determining the offsetWidth and scrollWidth for option elements within a select field containing the multiple attribute on Internet Explorer 11

My select input element has multiple attributes and a fixed width set. Unfortunately, due to the fixed width, the overflowing content in the x-direction is not visible. To address this issue, I have created a JavaScript function that uses the title attribu ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

Can you explain the distinction between object allocation using the '=&' operator and the Object.create() method?

I have been delving deep into JavaScript object operations. My question revolves around the difference between const me = Object.create(person); and const me = person;. Both of these operations provide a similar output as they reference the object to a new ...

Utilizing Vue.js for Tabs in Laravel 5.8

I am encountering an issue in Laravel while attempting to set up a Vue instance for tabs. Currently, only Tab 1 and Tab 2 are displayed without any content, and the tabs themselves are not clickable links. Could this problem be related to how I am calling ...

JavaScript for varying content that is dynamically loaded on a completely ajax-powered website

This post has been updated to address the issue more effectively with a refined concept and code (based on the responses provided so far) I am working on developing an ajax-driven website, but I have encountered some issues with multiple bound events. He ...

What is the best way to set an object's value to null in AngularJS?

Check out this code snippet var data={}; data={stdId:"101"}; data={empId:"102"}; data={deptId:"201"}; In my project, I'm receiving data from services into a data object with differing key names such as stdId or empId, etc. I need to set empty val ...

What happens in mongoose if one of several consecutive queries fails?

Currently, as I work on my API, I am utilizing two Models: SongModel and UserModel. Whenever a new song is saved, I also execute a query to link the song._id to the user who created it. Unfortunately, a mistake in my code caused the second query to throw a ...

What is the reason for Rich file manager to include filemanager.config.json instead of simply adding an image to the text

I have integrated Rich File Manager with Laravel 5.3.20 using the default configuration provided below: Javascript <script> CKEDITOR.replace( 'textarea', { filebrowserBrowseUrl: '{!! url('gallery/index.html& ...

Is it possible to locate and eliminate the apostrophe along with the preceding letter?

My objective is to tidy up a character string by removing elements that are not essential for the user and SEO, specifically the (letter before the apostrophes) in this case. I am looking for a regex solution or explanation of how to achieve this in PHP, a ...

Uniform Height for Several Selectors

I came across a script on Codepen created by RogerHN and decided to customize it for a project I'm currently working on: https://codepen.io/RogerHN/pen/YNrpVa The modification I made involved changing the selector: var matchHeight = function ...

Vanilla JavaScript code that utilizes regex to transform JSON data into an array of blocks, while disregarding any

As I searched through various resources on converting JSON into arrays using JavaScript, none of the results matched my specific requirements (outlined below). I am in need of a RegEx that can transform JSON into an array containing all characters such as ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

Learn the technique of initiating one action from within another with Next Redux

I'm looking to set up user authorization logic when the page loads. My initial plan is to first check if the token is stored in the cookies using the function checkUserToken. Depending on whether the token is present or not, I will then call another f ...