Utilize Var as Key in Vue 3.0

In my attempt to grasp this issue:

I have created a v-for loop like so:

<div v-for="playlistItem of playlists.PLDk0_ZYOcqxEq5ZxXAI5FiVL79hk2oSua.items">
        {{playlistItem.snippet.title}}
      </div>

As you can see, I am using the Playlist ID as the key in the playlists object and it is functioning correctly.

However, when I try the following:

 <div v-for="playlist of channel.items" :key="playlist.id">
  <div v-if="playlist.contentDetails.itemCount && playlist.status.privacyStatus === 'public'">
    <div>{{playlist.snippet.title}}</div>
    <div>{{playlist.id}}</div>
    <div>
      <div class="content">Content:</div>
      <div v-for="playlistItem of playlists[playlist.id].items">
        {{playlistItem.snippet.title}}
      </div>
    </div>
    <hr>
  </div>
</div>

The application throws an error saying "Cannot read property 'items' of undefined".

{{playlist.id}} displays the searched playlist, and when I use {{playlists[playlist.id]}}, it shows the object on the page.

But for some reason, {{playlists[playlist.id].items}} cannot be accessed. What am I missing?

Background:

<script>
// @ is an alias to /src
import channel from '@/../public/cache/channel.json'
import playlists from '@/../public/cache/playlists/'

export default {
  name: 'Home',
  components: {
    channel, playlists
  },
  data(){
    //console.log(channel)
    console.log(playlists)
    return{
      channel, playlists
    }
  }
}
</script>

The 'channel' contains YouTube channel data in JSON format, and for 'playlists', I have objects structured like this:

{
    "PLDk0_ZYOcqxEqFirstKey" : {"kind":"","etag:"","items":[...]},
    "PLDk0_ZYOcqxEqanotherKey" : {"kind":"","etag:"","items":[...]},
}

Essentially, I am trying to access the object from the 'playlists' object with the same ID as the current loop iteration to then iterate through its items: playlist."variableIdFromParentLoop".items

Code Sandbox Link : Code Sandbox

Answer №1

There may be some missing playlist IDs in the channel.items[] compared to the playlists data, causing instances where playlists[playlist.id] is undefined, resulting in the error you are seeing.

An effective solution could involve conditionally displaying the playlist information based on the existence of playlists[playlist.id]:

<template v-if="playlists[playlist.id]">
  <div class="content">Content:</div>
  <div v-for="playlistItem of playlists[playlist.id].items" :key="playlistItem.snippet.id">
    {{playlistItem.snippet.title}}
  </div>
</template>

Check out the demo here

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

The server response value is not appearing in Angular 5

It appears that my client is unable to capture the response data from the server and display it. Below is the code for my component: export class MyComponent implements OnInit { data: string; constructor(private myService: MyService) {} ngOnInit ...

Do you need the Tooltip Module for Angular-bootstrap popover to work properly?

"Could it be possible that my popover isn't working because it requires the tooltip module just like the Bootstrap jQuery plugin?" Is this the reason my popover isn't functioning as expected? What exactly is the tooltip module and do I need to i ...

methods for removing white spaces from json webservice output in asp.net

Hello everyone! I'm new to the world of JSON and this is my first experience with a webservice. I have successfully created an ASP.NET Webservice that returns JSON data. Everything seems to be working fine, but there is one issue I need help with. Wh ...

I am experiencing issues with the search feature in angular and node.js that is not functioning properly

Need assistance with debugging this code. I am currently working on adding search functionality to my Angular web page. However, when testing the code in Postman, I keep receiving the message "NO USER FOUND WITH USERNAME: undefined". Additionally, on the w ...

Including item from ajax not within $.when function finished

function fetchData(){ return $.ajax({ url : 'URL1', data : { id : id }, type : 'GET', }); } function fetchItemData(item_id) { return $.ajax({ url: 'URL2', data: { item_id: it ...

Retrieve the origin of the copied text

While working on a Vue application, I'm curious to know if it's possible to access the source of pasted text. For example, whether the pasted text originated from your own application, Word, or Notepad? I attempted the code below but was unable ...

Why is my Vue view not being found by Typescript (or possibly Webpack)?

npx webpack TS2307: Cannot locate module './App.vue' or its corresponding type declarations. I am currently utilizing webpack, vue, and typescript. My webpack configuration is pretty basic. It uses a typescript file as the entry point and gener ...

Creating a Carousel in Angular 2 Without Using External Libraries

I am attempting to create a custom carousel component for my Angular 2 project, however, I am unsure of how to proceed. Are you able to provide me with some examples without using any libraries such as ngx-bootstrap? ...

What could be causing the CSS to not display properly on specific routes?

I'm facing an issue where CSS seems to be working fine for certain routes with node.js & express, but not for others. It's puzzling because the HTML file links to the same CSS file in both cases. For instance, CSS works perfectly for the route " ...

Website header extends beyond normal boundaries, exceeding 100% width

Here is the CSS code I used for styling the header: #header { font-size: 3rem; width: 100%; height: 4.5em; display: flex; align-items: center; padding-left: 1em; } Despite setting it to 100% width, on the website it displays with a ...

Is it possible to automatically mute an HTML 5 video when closing the modal?

Is there a way to pause a video that plays in a modal and continues playing in the background when the modal is closed? I am using the Materialize library. <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <!-- Compiled ...

Transforming the JSON body request from Postman into a Jmeter body request

const today = new Date(); const time = today.getTime(); pm.environment.set('time', time); let eventArray = []; for(let i = 1; i <= 50; i++) { let t = time + (i * 1000); eventArray.push({ "eid": i, "time": t }); } con ...

Utilizing multiple components onEnter with React-router for authentication scenarios

I am currently working on an app that consists of 2 components for a single path. The routes are as follows: <Router history={hashHistory}> <Route path="/" component={AppContainer} onEnter={requireEnter}> <Route path="/homepage" ...

How can the key values of a Prolog dictionary be utilized within a predicate?

Having some trouble here with a simple question that I just can't seem to find the answer to. I'm currently working on an API that reads JSON and successfully converts it into a dictionary using http_read_json_dict. The issue I'm facing is f ...

access various paths to distinct iframes

<?php // Specify the directory path, can be either absolute or relative $dirPath = "C:/xampp/htdocs/statistics/pdf/"; // Open the specified directory and check if it's opened successfully if ($handle = opendir($dirPath)) { // Keep readin ...

Concealing a section of a table with JavaScript while preserving the original table structure

I made some adjustments to the script tag: $(document).ready(function) { Now, the evenTd's are hidden correctly. Here is the table with the code provided: <table> <tr> <td>itemOne</td> <td class="even ...

Ways to retrieve node from openweathermap information

I'm trying to extract the weather description from a JSON output in an angular view. I've managed to get the temperature using {{weatherdata.main.temp}} and the wind speed using {{weatherdata.wind.speed}}. However, the weather description is form ...

What is the best way to update my logo and incorporate a colored border at the bottom of my fixed header while the user is scrolling down?

After spending countless hours researching online, I've been struggling to implement header effects on scroll without using JavaScript. My goal is to achieve a simple effect where the header reduces in height, the logo changes, and a colored border is ...

What is the best way to split text copied from a textarea into <p> paragraphs with an equal number of characters in each?

Check out this JSFiddle version I've found a JSFiddle example that seems perfect for my current project needs. However, I'm wondering how to modify the code to ensure that each paragraph is evenly divided with the same number of characters and a ...

Breaking down nested dictionary into separate columns within a pandas DataFrame

I am facing a challenge with two data frames that have a column named 'author' with different formats: df1 author {'name': 'Reuters Editorial', 'url': None} df2 Authors {:name ""Arjun Sidharth"", ...