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

Converting a curl command to a $.ajax() call in JavaScript: A step-by-step guide

I'm attempting to retrieve data from the Zomato API by using jquery ajax, however, they have provided a curl command instead. curl -X GET --header "Accept: application/json" --header "user-key: key" "https://developers.zomato.com/api/v2.1/cities" Is ...

Having difficulty applying capitalization to the initial word in an input using JavaScript/jQuery

I've read through several other discussions on this forum regarding the same issue. My problem lies in capitalizing the first letter of an input. Here is the link to my code on JSFiddle Despite my efforts, I can't seem to get the substr() funct ...

How to selectively make properties optional in Typescript conditions

Currently, I am working on creating a utility type to unwrap nested monads of Options in my code. Here is the progress I have made so far: export interface Option<T> { type: symbol; isSome(): boolean; isNone(): boolean; match<U>(fn: Mat ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

What's the issue with my jQuery AJAX script?

I am experiencing an issue with my ajax pages using jQuery to retrieve content. Only one page seems to be working properly, even though I have multiple pages set up. How can I resolve this problem? $(document).ready(function() { $('.lazy_content& ...

Having trouble sending data to an API through jQuery: the function is not functioning properly

Currently, I am in the process of developing an HTML form that allows users to input values into text fields and submit them to an external API called ThingSpeak. This API then uses the received values to generate a plot displayed within an iframe. Althoug ...

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

Bring in typings from a package with an alternate title

I have a project that I am currently converting to typescript. In this project, I am using the package ng-idle. Additionally, there is a corresponding @types package named angular-idle, which contains the file @types/angular-idle/index.d.ts with the follow ...

The constructor error in ng-serve signalizes an issue in

Currently, I am developing an AngularJS application. However, when attempting to start the dev server, I encountered an issue with my ng serve command: https://i.stack.imgur.com/QujSe.png ...

Using AngularJS to encapsulate an externally loaded asynchronous library as a service

Is there a way to wrap a 3rd party library that loads asynchronously into an Angular service? What is the best practice for incorporating such libraries as services in Angular? Currently, I am approaching it like this: angular.module('myAPIServices ...

Command in Selenium Webdriver for initiating a mouse click

Currently, I am in the process of writing tests for a Java application that has been created with the Vaadin framework. To conduct these tests, I have opted to utilize the Robot Framework. In certain instances, I must implement robot framework commands suc ...

The Vuejs progressive web app service worker is failing to function offline when deployed on Heroku

I created a website using vuejs and included pwa support to make it work offline. The website is hosted on heroku and was functioning properly until recently when it suddenly stopped working offline for no apparent reason. When I run it on a local server, ...

Unveiling the power of Axios and Vue in fetching API data: The quest for

I've encountered a problem while trying to integrate my API with Vue/Axios. The issue arises when I attempt to store the data retrieved by Axios into an empty variable within the data object of my component. It throws an "undefined at eval" error. Can ...

Looking to update the key name in a script that produces a list sorted in ascending order

I have been working on code that iterates through a flat json document and organizes the items into a hierarchical structure based on their level and position. Everything is functioning correctly, but I now need to change the name of the child elements to ...

Discover the most frequent value in an array by utilizing JavaScript

My array contains repeating values: [0, 1, 6, 0, 1, 0] How can I efficiently determine the highest frequency of a specific value being repeated? For example, in this array, I would like the script to return 3 since the number 0 repeats most frequently a ...

Stop extra properties from being added to the return type of a callback function in TypeScript

Imagine having an interface called Foo and a function named bar that accepts a callback returning a Foo. interface Foo { foo: string; } function bar(callback: () => Foo): Foo { return callback(); } Upon calling this function, if additional pr ...

Is it possible to use Firebase auth.user in order to retrieve the signed-in user directly?

As I develop a webapp with NextJS v13.4 and firebase as my backend using the firebase web modular api, I came across a statement in the documentation: "The recommended way to get the current user is by setting an observer on the Auth object." ...

Unexpected Issues with the Ant Design Sidebar Layout Demo

My React webapp is utilizing the Ant design component framework version 4. I attempted to integrate this example from the Antd documentation into my webapp: https://codesandbox.io/s/ymspt However, when I implemented the code in my webapp, the result didn ...

Dealing with shared content in your Capacitor Android application may require some specific steps

As a beginner in android development, I am currently embarking on my first Capacitor Android app project using Quasar/Vue. My goal is to enable the app to receive files/images shared from other apps. Through research, I have discovered how to register my a ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...