Error message: Attempting to access index 0 of an undefined property within a Vue.js v-for loop

The return of console.log(this.sights) is an array containing 20 objects, each with properties such as name, photos, references, etc. My current goal is to iterate through these objects, displaying their names and photo_references. Here is how I am attempting to accomplish this:

<div @click='selectSight(index)' v-for='(sight, index) in sights'>
    {{ sight.name }}
    {{ sight.photos[0].photo_reference }}
</div>

The above code successfully displays the sight.name. However, I encounter an error message:

"Error in render: "TypeError: Cannot read property '0' of undefined"".

I attempted manual access as follows:

console.log(this.sights[0].photos[0].photo_reference)

This returns the photo_reference, indicating the properties are correct. So, where am I making a mistake?

Below is the structure of the array:

(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
    0:
        geometry: Object
        icon: "https://maps.gstatic.com/mapfiles/place_api/icons/museum-71.png"
        id: "975708e853f136200f2229c793df9070707b842e"
        name: "National Museum of Modern Art, Tokyo"
        opening_hours: Object
        photos: Array(1)
            0:
                height: 3456
                html_attributions: Array(1)
                photo_reference: "CmRZAAAA60seVRHbzyg3TPIUPEUaDbzI2-TpMB3cB3bC8BYG_gRrJwmwSVY1Mcl1PBo0U0CMwmqssyQw4w2iHyh6ze3iQaiXdsveolGBovi3rGZTgvKjTV9PRt-WDieYrwoRy1z0EhBsZitey_MyjiwrYK_Sol3eGhSfOpXUpLc-3RYeJjz2JKMMXYNZYw"
                width: 4608

Answer №1

The reason for the error you are seeing is that some of the objects contain sight.photos as undefined. One way to handle this is to include a conditional check before trying to access the first element:

<div @click='selectSight(index)' v-for='(sight, index) in sights'>
    {{ sight.name }}
    {{ sight.photos && sight.photos.length > 0 ? sight.photos[0].photo_reference : '' }}
</div>

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

An error occurred as the Serverless Function timed out while attempting to load a dynamic route in Next.js version 13

I have a basic Next.js application with the following route structure: /contentA/ - Static - Initial load: 103 kB /contentA/[paramA]/groups - SSG - Initial load: 120 kB /contentB/[paramA]/[paramB]/[paramC] - SSR (client component) - Initial load: 103 kB ...

Steps for moving data from a JavaScript variable to a Python file within a Django project

I have created a unique recipe generator website that displays each ingredient as an image within a div. When the div is clicked, it changes color. My goal is to compile the ids of all selected divs into one array when the submit button is clicked. I have ...

Utilizing a Multidimensional Array for manipulating multiple rows and columns simultaneously

Recently, I encountered a peculiar issue while working with Python. The code snippet below is intended to generate a plot of locations where an object has traveled: def GoForward(self, duration): if (self.TowardsX - self.X == 0): Myro.robot.mo ...

Managing iframes in React using reference methods

Trying to set the content of an iframe within a React component can be a bit tricky. There is a component that contains a handleStatementPrint function which needs to be called when the iframe finishes loading. The goal is to print the loaded iframe conten ...

What sets apart $document from $window.document in Angular?

After experimenting with the code on JSBin, I noticed that the first snippet successfully retrieved the canvas object, while the second one did not. JSBin: http://jsbin.com/natavejasa/1/edit?html,js,output var canvas = $window.document.getElementById(&ap ...

Encountered difficulty accessing the controller ActionResult from JavaScript代码

Resolution: After thorough investigation, I successfully identified and resolved the issue. Surprisingly, it was not related to the Javascript or Controller code as initially anticipated. The root cause stemmed from a .dll file that was causing discrepanci ...

I've been struggling with this javascript error for three days, how can I finally resolve it?

Currently developing a website using react js, but encountering an error every time I try to push to my github repository. Run npm run lint npm run lint shell: /bin/bash -e {0} <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Using jQuery to dynamically update the CSS of one table column depending on the attribute of another column

Welcome to my HTML table <!DOCTYPE html> <html> <body> <table> <thead> <th>Title1</th> <th>Title2</th> </thead> <tbody> <tr> <td><input type="checkbox" id=0 /></td> ...

How can I update a CSS class value by utilizing AngularJS variables?

I am currently facing an issue with making my CSS values dynamic. The code I have tried is not functioning as expected. <style> .panel-primary { background-color:{{myColorPanel}} } </style> I came across a similar query on Ho ...

data not populating in datagrid upon first load

I'm facing an issue where the data I'm trying to fetch using an API is not initially loading in my datagrid. I can retrieve the data successfully, but for some reason, it doesn't show up in the datagrid. The setup involves a common function ...

When making a fetch call in React, the response is the index.html file but Chrome displays an error saying Uncaught (in promise) SyntaxError: Unexpected token < in JSON

I have been encountering an issue while trying to retrieve data from my local express server and displaying it using React. The problem appears to be that instead of fetching the data, the index.html of the React app is being returned. In the network tab o ...

Leverage jQuery to automatically submit an ajax form once all ajax requests have been successfully executed

I have integrated a WordPress plugin for store locator on my website. For pages without the interactive map, I have set up a form that serves as a location search tool. To clarify, the form includes a location field where users can input their desired loc ...

CSS or jQuery: Which is Better for Hiding/Showing a Div Within Another Div?

Show only class-A at the top of the page while hiding all other classes (x,x,c). Hide only class-A while showing all other classes (x,x,c). Is it possible to achieve this? <div class="x"> <div class="y"> <div class="z"&g ...

Understanding the scope of variables in a JavaScript callback function

I am attempting to send an object variable to a callback function const sql = require('mssql'); const asset_update = function (connection, addr) { this.connection = connection; this.addr = addr; this.addr_long = parseInt(addr, 16); } ...

Executing jQuery callback functions before the completion of animations

My issue revolves around attempting to clear a div after sliding it up, only to have it empty before completing the slide. The content I want to remove is retrieved through an Ajax call. Below you will find my complete code snippet: $('.more& ...

"Incorporating JSON and Ajax to dynamically populate one select based on the selection in another select

I need to display data from a JSON file in select options, and here is the structure of my JSON file: [{ "vehicle": "car1", "type": [ {"name" : "BMW", "details" : [{ "color" : "red", "price" : "50000" }, ...

Is there a way to display a foundation.css drop-down menu using jQuery?

After attempting to create a navigation bar using foundation.css, I encountered an issue where the sub-menu does not appear when hovering over it with the mouse. The main question at hand is how to display the sub-menu of test on this specific webpage. D ...

Troubleshooting a Messaging Error between Background and Another Script

Attempting to transfer selected text from the current page to an HTML page using message passing: content script to background script, then background script to the HTML page. However, encountering errors if the HTML page is not already open, and even gett ...

Populate a numpy array with NaN values

I am working with a numpy vector called my_indexes, which is of size 1XN and contains boolean values for indexing. Additionally, I have a 2D array named my_array with a size of MxK, where K is much smaller than N. The boolean vector represents columns that ...

Issue with Javascript functionality not persisting after page reload initiated with a href = '#'

I am facing an issue with a button on my webpage that is meant to redirect and reload the home page. However, after redirection to '#', my JavaScript seems to stop functioning correctly. Currently, my JavaScript code is enclosed within window.on ...