Having trouble retrieving the property of JSON data in VueJS while using a loop index?

My VueJS app showcases activity data fetched from Strava, organized by week throughout a span of 20 weeks. I am facing a challenge where the API object is visible but inaccessible for each property.

Here are some key snippets from the Single File Component (SFC).

DATA

weekly_total_data will continue to expand as the weeks progress

data() {
        {
            return {
            activity_weeks: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
            weekly_total_data:
               [{"week_number":3,"total_distance":39877.6,"total_moving_time":11841},
                {"week_number":2,"total_distance":58596.4,"total_moving_time":18719},     
                {"week_number":1,"total_distance":41347.5,"total_moving_time":12796}]
            }
        }
    }

FUNCTION

Accessing the data

    matchWeeklyTotals(){
        var x = this.weekly_total_data
        console.log(x)
        return x
      }
    },

TEMPLATE

Iterating through the weeks, obtaining an index for each week, and utilizing it to showcase the relevant data per week

<div v-for="(week, week_index) in this.activity_weeks" v-bind:value="week._id">
   <div class="container max-w-xl mx-auto">
       <h2 class="text-2xl">Week {{week}}: {{ (matchWeeklyTotals()[week_index])}}</h2>
   </div>
</div>

Currently, I can exhibit the object, but when attempting

matchWeeklyTotals()[week_index][total_distance]
, it results in failure. Various attempts with JSON.parse have also been made.

Any assistance on accessing the total_distance and total_moving_time would be greatly appreciated.

Answer №1

The code below is fully operational.

I am currently filtering the data in weekly_total_data to verify if the activity_weeks are present, specifically looking at the week_number.

<script setup>
const activity_weeks = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

const weekly_total_data = [
  {"week_number":3,"total_distance":39877.6,"total_moving_time":11841},
  {"week_number":2,"total_distance":58596.4,"total_moving_time":18719},
  {"week_number":1,"total_distance":41347.5,"total_moving_time":12796}
]

const matchWeeklyTotals = () => {
  var x = weekly_total_data
  console.log(x)
  return x
}

</script>

<template>
  <div v-for="week in weekly_total_data.filter(x => x.week_number in activity_weeks)">
     <div class="container max-w-xl mx-auto">
         <h2 class="text-2xl">Week {{week.week_number}}: {{ week.total_distance }}</h2>
     </div>
  </div>
</template>

Answer №2

If my interpretation is correct, you have the option to utilize optional chaining:

const app = Vue.createApp({
  data() {
    return {
      activity_weeks: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
      weekly_total_data: [
        {"week_number":3,"total_distance":39877.6,"total_moving_time":11841},
        {"week_number":2,"total_distance":58596.4,"total_moving_time":18719},     
        {"week_number":1,"total_distance":41347.5,"total_moving_time":12796}
      ]
    }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="(week, week_index) in activity_weeks" v-bind:value="week._id">
    <div class="container max-w-xl mx-auto">
      <h2 class="text-2xl">Week {{ week }}:</h2>
      <p>{{ weekly_total_data[week_index]?.total_distance }}</p>
      <p>{{ weekly_total_data[week_index]?.total_moving_time }}</p>
    </div>
  </div>
</div>

Answer №3

Ensure that when accessing data through a getter, it is set up as a computed property

export default {
...,
computed: {
matchWeeklyTotals() {
return this.weekly_total_data;
}
}
}

Remember to access the data in the template without using parenthesis, directly like this:

<h2>
{{ (matchWeeklyTotals[week_index])}}
</h2>

It is recommended to check if the item at weekIndex exists and try to match the week_number value by using functions like find or mapping the array for direct data access, especially if there might be sorting issues in the future. You can also consider mapping the weekly_total_data array directly unless having multiple arrays serves a specific purpose

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

Automatically trigger the expansion of all panels within Vuetify using code

I'm attempting to use Vuetify 2.3.5 to programmatically control the opening and closing of expansion panels. <v-expansion-panels accordion> <v-expansion-panel v-for="(item,i) in faqs" :key="i"> <div class ...

What are the steps to utilize the feature of "nprogress"?

After successfully installing npm install nprogress in my project, I encountered an issue when trying to refresh the page - the console displayed the following message: hot-dev-client.js:182 [Fast Refresh] done hot-dev-client.js:196 [Fast Refresh] rebuildi ...

What is the best way to prevent a selected <option> in one <select> from being selected in another <select>, while also making sure this applies to both new and existing &

Currently, I am working with a code snippet that disables select options based on similar fields. The code can be found here. $(document).on('shown.oc.popup', function() { let options = $('.variantPlacementOptions:first select').c ...

Make a deep clone in JavaScript while also altering the parent node's type and name

I am looking for guidance on how to clone a Node and then convert its nodeName, ensuring that the attributes are copied along with the children deeply. I want to achieve something similar to switching an existing span element to a div while retaining all i ...

Struggling with setting up Vue.js

Having trouble installing Vuejs and encountering an error message: What mistake am I making and how can I successfully install it? Tried reinstalling Node.js and updating npm. C:\Users\chris>npm install -g @vue/cli C:\.node_modules&bso ...

The add function in Sequelize Many-to-Many relationships does not properly execute

dependency.json "express": "^4.17.1", "pg": "^7.17.1", "pg-hstore": "^2.3.3", "sequelize": "^5.21.3", We have defined two models: // User Schema const User = seq.define('user', { id: { type: Sequelize.INTEGER, autoIncrement: ...

Enhancing the accessibility of Material UI Autocomplete through a Custom ListboxComponent

I have developed a custom ListboxComponent for the MUI Autocomplete component in MUI v4. How can I ensure that it meets the necessary accessibility requirements, such as navigating through options using the arrow keys? <Autocomplete ListboxComponent ...

Set the title attribute according to the content of the <p> tag

Recently, I encountered a situation where I had numerous p tags with a specific class (let's call it .text). My task was to include the title attribute containing the text of each tag. For example: <p> Hello, world </p> This would resul ...

Retrieve the timestamp difference by querying mongoDb

Looking for a way to subtract days from a Date field. I tried the following query: {"lastSeen": { "$gte": {"$date": { $subtract: [ "$date", 1616000000 ] }}}} Unfortunately, it didn't work and I encountered an e ...

Prevent draggable function in jQuery-UI for specific elements

I'm in the process of creating a website that mimics a desktop interface, and I want to be able to easily move around the windows. To achieve this functionality, I am incorporating jQuery-UI along with the .draggable() method. My current HTML structur ...

Executing a group query for Mongoose in a node.js/express route

Hey there, I have a query that works perfectly fine in Robomongo. Here's the code: db.av.group( { key: { roomId: 1}, cond: { dateOfDay: { $gte: new Date('12/01/2014'), $lt: new Date('12/30/2014') } }, reduce: function( curr, re ...

Learn the process of retrieving a file from server.js and showcasing it on an HTML page

I am currently developing a YouTube video downloader using express, HTML, and JavaScript, with plans to transition to Vue.js in the future. Here is a snippet of my code: Index.html <!DOCTYPE html> <html lang="en"> <head> & ...

Saving access and refresh tokens in Django after receiving a response from Google API

My LMS application is built using Django REST and Vue.js. I authenticate users through Google OAuth2 by: utilizing drf-social-oauth2 on the backend with Google as the authentication provider implementing this wrapper for gapi on the frontend The user cli ...

What are the steps to utilize DOMParser in next.js?

When it comes to manipulating an HTML string, in VanillaJS you would typically do something like this: let stringHTML = '<p>hello</p> <style> p{ ...

JQuery .click Event doesn't center elements even with transform-origin adjustment

In the JSfiddle provided below, you can see that after a click event occurs, two span (block) elements rotate 45deg to form an "X". However, both elements are slightly shifted left, creating an off-center "X" relative to the parent's true center-origi ...

Generate a customizable button in Bootstrap using JavaScript extensions

After some investigation on Bugzilla, I discovered that by setting the options URL in install.rdf to arbitrary JavaScript, it can run smoothly. However, a strange issue arises where the window deactivates, as if an invisible dialog has appeared over it, ma ...

What is the best situation to utilize $(document).ready()?

After observing that using $(document).ready(..) seems to introduce a noticeable delay in applying JavaScript effects, I've been contemplating the best approach. I know that simply placing the effect in a <script> tag may not work if the DOM isn ...

The Json iteration loop is displaying the term "object" rather than the actual data within it

I'm trying to use the foreach loop in JSON and then display it with innerHTML. No errors are showing up, but the problem I'm facing is that the output is showing like this: [object Object] Instead of what is supposed to be displayed in the fo ...

Record all GraphQL responses using Express

After successfully implementing logging for GraphQL errors using the provided code: app.use('/graphql', graphqlHTTP(request => { return { schema, rootValue: { request }, formatError: error => { const params = ...

Alter Text Using Typewriter

Recently, I have been experimenting with code on my glitch website, trying to create typewriter text. Thanks to help from a user on StackOverflow, I was able to achieve this effect successfully. However, I am now facing a new challenge. My goal is to make ...