Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed:

Dynamically access object property using variable

Dynamically access object property using variable

The key point that caught my attention was @chacham15's response mentioning "careful with this: javascript compilers will error here since they don't rename strings but they do rename object properties."

If that's the issue, how can I resolve it?

My goal is to dynamically access the

this.$store.state.countries.spain.name
property, allowing me to access properties such as spain, germany, and others. I have tried various methods:

this.$store.state.countries[""+name].name
this.$store.state.countries[this.name].name
this.$store.state.countries[name].name
this.$store.state.countries[`${this.name}`].name
this.$store.state.countries[`${name}`].name

I even attempted creating a function that takes the name variable and assigns it to a constant variable within the function, but still no success. The name variable is a string and I can log it correctly without any issues, which makes it confusing as to what might be causing the problem.

It only returns the property when I use

this.$store.state.countries["spain"].name
, confirming that the property exists and can be accessed without errors. My struggle arises when trying to access the property using a variable.

This is the code snippet in question:

<template>
    <tr class="stats-row">
        <td :title="`${name}`">{{name}}</td>
        <td>{{this.$store.state.countries[this.name]}}</td>
    </tr>
</template>
        
<script lang="ts">
import Vue from 'vue';
        
export default Vue.extend({
    name: 'StatsRow',
    components: {
    },
    props: {
        name: String,
    },
});
    
</script>

And here is the parent Vue file:

<template>
    <div class="stats">
        <table>
            <StatsRow v-for="el in this.$store.state.countries" v-bind:key="el.neutral" :name="el.name"/>
        </table>
    </div>
</template>
    
<script lang="ts">
import Vue from 'vue';
import StatsRow from '@/components/StatsRow.vue';
    
export default Vue.extend({
    name: 'Stats',
        components: {
        StatsRow,
    },
});
</script>

Answer №1

My solution involved passing all the elements as props from the parent component.

Below is the child component:

<template>
  <tr class="stats-row">
    <td :title="`${name}`">{{name}}</td>
    <td>{{newCases}}</td>
    <td>{{totalCases}}</td>
    <td>{{newDeaths}}</td>
    <td>{{totalDeaths}}</td>
    <td>{{newRecovered}}</td>
    <td>{{totalRecovered}}</td>
  </tr>
</template>

And here is the parent component:

<template>
  <div class="stats">
    <table>
      <StatsRow v-for="el in this.$store.state.countries" v-bind:key="el.name" :active="el.active"   :name="el.name" :color="el.color" :showCases="el.showCases" :showDeaths="el.showDeaths" :newCases="el.newCases" :totalCases="el.totalCases" :newDeaths="el.newDeaths" :totalDeaths="el.totalDeaths" :newRecovered="el.newRecovered" :totalRecovered="el.totalRecovered"/>
    </table>
  </div>
</template>

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

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

Error message: "Unexpected token" encountered while using the three.js GLTFLoader() function

I have a requirement to load a .glb model into three.js by using the GLTFLoader. I was able to successfully create a rotating 3D mesh on a canvas without encountering any errors in the console. However, when I tried to replace it with the .glb model, I enc ...

Creating a VueJS Web App that is Distributable and Distributed

My challenge is to develop a distributable app using VueJS for four different companies, each with their own unique products database and custom settings. These companies want to integrate a page on their websites that displays their specific catalogue wit ...

Error occurs when attempting to reference an object from an NPM package

Currently, I'm attempting to utilize the https://github.com/iamcal/js-emoji library for colon-to-emoji conversion. Following the installation of its NPM package, I included <script src="../node_modules/emoji-js/lib/emoji.js" type="te ...

What is the best way to set up multiple routes for a single component in React

I am currently using Vue 2 in my project and have set up the following routes: const routes = [ { path: "/suites", component: Home, }, { path: "*", component: LandingPage, }, ]; Now, I need to include an additi ...

Verify if the user is already present in the MongoDB database and authenticated with Passport

I'm currently exploring the usage of passport and I am in the process of setting up a "register" page functionality. The registration process is working smoothly, along with the log-in form. Yet, I am looking to implement a validation to check if the ...

Error encountered when trying to access the _id property in React Components using MongoDB and passing a Key: TypeError - Property _id is undefined

I've encountered an issue when trying to pass a field from MongoDB into a React Component. Here is the snippet of code I'm working with: import React from 'react'; import ReactDOM from 'react-dom'; import { Meteor } from &apo ...

Can you explain the significance of using square brackets in the typescript enum declaration?

While reviewing a typescript file within an Angular ngrx project titled collection.ts, I came across the declaration of enum constants. import { Action } from '@ngrx/store'; import { Book } from '../models/book'; export enum Collecti ...

`How can I integrate ScrollMagic into my Nuxt project?`

I've been working on integrating ScrollMagic into my Nuxt project. I followed the tutorial provided in this linked article: https://nuxtjs.org/guide/plugins. I included ScrollMagic.js in nuxt.config.js, but encountered an error stating: ReferenceError ...

Streamlining a complex task in JavaScript

I am currently exploring options to streamline my code so that I don't need to repeat the same function 38 times. Instead, I would like to have a single function that can handle 38 different IDs separately. The script is designed to randomly select a ...

Extract the value from an array of objects

https://i.sstatic.net/fTShc.png Having some difficulty accessing the elements of an array. In order to assign a project name to a local variable projectName, I am seeking assistance with extracting the project name from the given JSON structure. Any hel ...

Having trouble with your custom accordion content in React JS not sliding open?

Check out my progress so far with the fully functioning view here This is the structure of the Accordion component: const Accordion = ({ data }) => { return ( <div className={"wrapper"}> <ul className={"accordionList ...

After successfully uploading a file, refresh the file list using AngularJS, DropzoneJS, and JSON

In my "file manager page," I am using DropzoneJS for uploading files and AngularJS ng-repeat to display all the saved files. The file list is retrieved through an ng-controller that uses an http.get request to fetch a JSON file with the file list. When Dr ...

The onClick() function in JavaScript is encountering issues on the Firefox OS mobile application

I've been working on an app for Firefox OS mobile devices where I'm trying to trigger a Javascript function onClick() from a div attribute. It's functioning properly in regular browsers, but when I test it in the simulator, the onClick funct ...

Using ng-repeat in Angular JS to generate forms

Having just recently delved into angular JS, I began working on it a mere week ago. Utilizing the Angular-UI Bootstrap Tabs directive in my application, upon load, a grid displaying a list of records is presented within a static tab. Once a user selects a ...

Tips for effectively passing a $scope object between various controllers

I am encountering an issue with sharing a $scope object between two controllers. Within the 'IssueBookCtrl' controller, I update the 'books' object element value like this: $scope.books[i].issued = true; After that, I use the $emit s ...

Utilizing req.session in an Express application with Angular (written in TypeScript) when deploying the backend and frontend separately on Heroku

I'm currently facing an issue where I am unable to access req.session from my Express app in Angular. Both the backend and frontend are deployed separately on Heroku. I have already configured CORS to handle HTTP requests from Angular to my Express ap ...

How can I save a PDF file using React?

My webpages contain several tables, and I am looking to add a dropdown feature that allows users to choose between saving the table in either PDF or Excel format. These tables are dynamically generated with the header structured in array form and data sto ...

Creating a multi-filter gallery similar to the one found in WooCommerce or eCommerce platforms involves integrating various filters to allow

Looking for a dynamic multifilter gallery similar to WooCommerce/ecommerce product filters? We have three types of filter dropdowns: COLOR, SIZE, and SHAPE. For example, if you select color: red and green, size: small, and shape: round The filtering wil ...

The first name of the user is not shown following the completion of the registration

I'm currently developing an application using React and Node.js. In the frontend, I have implemented a functionality where upon logging in, users are redirected from the /login route to the root route and greeted with their first name. However, when a ...