Storing dataset characteristics in a JSON file utilizing Vue.js form response

I am currently working on creating a JSON file to store all the answers obtained from a Form. Some of the input fields have an additional dataset attribute (data-tag). When saving the Form, I aim to extract these 'tags' and include them in the JSON file as keys with the input values as their corresponding values. My approach involved referencing these inputs and using $refs to obtain the tag name.

However, I encountered an error:

Error in v-on handler: "TypeError: Cannot read property 'push' of undefined"

To address this issue, I am trying to store the 'tags' in a separate array and then merge it with the Form Output.

If you have any alternative solutions or ideas, please share as I'm open to suggestions.

  • Vue.js version: 2.6
  • vuetify.js version: 2.3

List of Form inputs:

<v-text-field label="ICD" id="pos_t_1" name="pos_t_1" ref="icd" data-tag="icd_tag" v- 
  model="textfield" hide-details="auto" />

<v-radio-group v-model="radio" hide-details="auto" row>
  <v-radio
    v-for="radio in group"
    ref="radioGroup"
    :key="radio.id"
    :id="radio.id"
    :name="radio.id"
    color="primary"
    :data-tag="radio.tag"
    :label="radio.text"
    :value="radio.text"
  >
 </v-radio>
</v-radio-group>

Script:

export default Vue.extend({
name: 'Test',
data: function () {
    return {
        tags: [],
        radio: '',
        group: [
            {id: 'pos_r_2', text: 'Radio 1', tag: 'radio_tag_2'},
            {id: 'pos_r_3', text: 'Radio 2', tag: 'radio_tag_3'},
            {id: 'pos_r_4', text: 'Radio 3', tag: 'radio_tag_4'},
            {id: 'pos_r_5', text: 'Radio 4', tag: 'radio_tag_5'},
        ],
    }
},
methods: {
    onSubmit() {
        Object.keys(this.$refs).forEach((value) => {
           const refs = this.$refs[value];
           if (Array.isArray(refs)) {
               for (let i = 0; i <= this.$refs[value].length; i++) {
                   let key = this.$refs[value][i].$attrs['data-tag']
                   this.tags[key].push(this.radio)
               }
           } else {
               let key = this.$refs[value].$attrs['data-tag']
               this.tags[key].push(this.textfield)
           }
        })
    }
}
})

JSON structure of Form's output:

  [{
     "pos_t_1":"Test",
     "pos_r_2":"",
     "pos_r_3":"Radio 3",
     "pos_r_4":"",
     "pos_r_5":"",
  }],

Desired JSON structure:

  [{
     "pos_t_1":"Test",
     "icd_tag":"Test",
     "pos_r_2":"",
     "radio_tag_2":"",
     "pos_r_3":"Radio 3",
     "radio_tag_3":"Radio 3",
     "pos_r_4":"",
     "radio_tag_4":"",
     "pos_r_5":"",
     "radio_tag_5":"",
  }],

Answer №1

Attempting to push to an empty array without a specified key will result in an undefined value.

For instance, if you initialize tags = [] and then attempt to push tags[key].push(value), you won't be able to because tags[key] is not defined.

To address this issue, make the following changes to the onSubmit method:

onSubmit() {
        Object.keys(this.$refs).forEach((value) => {
           const refs = this.$refs[value];
           if (Array.isArray(refs)) {
               for (let i = 0; i <= this.$refs[value].length; i++) {
                   let key = this.$refs[value][i].$attrs['data-tag']
                   this.tags[key] = this.radio
               }
           } else {
               let key = this.$refs[value].$attrs['data-tag']
               this.tags[key] = this.textfield
           }
        })
    }

Answer №2

Big shoutout to @Donkarnash for showing me this cool trick:

            Object.keys(this.$refs).forEach((value) => {
            const refs = this.$refs[value];
            if (Array.isArray(refs)) {
                for (let i = 0; i < refs.length; i++) {
                    let key = refs[i].$attrs['data-tag']
                    if (refs[i].isActive === true) {
                        this.tags[key] = this.radio
                    }
                    else {
                        this.tags[key] = ''
                    }
                }
            } else {
                let key = refs.$attrs['data-tag']
                this.tags[key] = this.textfield
            }
        })

Sharing this in case it helps someone else too.

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 complexities of stopPropagation() causing further confusion

I have encountered an issue with my code. It currently allows a dropdown functionality for a <ul> element, but when a child <li> is clicked, it also closes other menus of the same type. To fix this, I used an if clause to check if the clicked ...

Displaying an image on canvas while showing a loading progress bar

I'm attempting to utilize this function to load an image into my canvas: function handleImage(e) { var reader = new FileReader(); reader.onload = function (event) { var img = new Image(); // img.onprogress = function (e) { ...

Using Laravel and Vue.js to create a looping function

My objective is to loop through a set of news items one at a time, and after completing this cycle 8 times, retrieve updated data and repeat the process. I am aware that there are a maximum of 8 news items available, each of which may contain either a vide ...

Exploring how to access properties of objects in javascript

As a novice on this platform, I'm uncertain if the title may be deceiving, but I have a question regarding the following scenario: var someObject ={} someObject.info= { name: "value" }; How can I acce ...

Creating a Utils class in Vue.js with seamless access to Vuex through this.$store

I have a situation where I need to retrieve state from the Vuex store using this.$store. After some research, I discovered that creating a custom plugin with an installed instance method might be the solution. Here is my plugin implementation: index.ts i ...

The putImageData function claims that the given object is not an ImageData object, but upon inspection in the console, it clearly displays that it is

After using getImageData to store the pixels of an image in a two-dimensional array, I attempted to draw them with putImageData. However, I encountered an error indicating that the first parameter is not of type ImageData. Strangely, when I logged the vari ...

How can I ensure that PrimeNG is functioning properly?

I'm encountering some difficulties setting up PrimeNG correctly to utilize its rich text editor. Despite installing all the necessary components, it's still not functioning as expected. https://i.stack.imgur.com/4kdGf.png This is my package.jso ...

Struggling to properly interpret the unrefined data from Typeform's webhook

Utilizing the webhook feature of Typeform to convert results to JSON when a user submits the embedded survey is working perfectly when tested with RequestBin. However, after exposing my local app using ngrok with the command ngrok http 3000 and setting t ...

The property this.props.Values is not defined

I'm facing an issue with a page. Specifically, I am working with the value: this.props.CategoriesList. This value represents a list of categories. The problem is that when I click on a button to navigate to the page where this value is used, it shows ...

Is there a way to eliminate the # sign from hash data using jQuery?

Can anyone help me retrieve the hash value from the URL? var hash = window.location.hash; I am looking for a way to remove the "#" sign from the hash. Any suggestions? ...

I'm baffled as to why this code isn't functioning properly

My current script seems to be malfunctioning for some reason. I'm using a combination of express, socket.io, jade, and node.js in this setup. Below is the script I am working with: var socket = io.connect(); function addMessage(msg) { var currentDa ...

Refresh all tabs in the TabContainer

I have implemented multiple tabs using dojo on a web page, and I need to refresh the current tab every 5 seconds without refreshing the entire page. You can check out the code in this fiddle: http://jsfiddle.net/5yn2hLv9/4/. Here is an example of the code ...

Encountering a memory issue when trying to parse a hefty JSON file using the Jackson library in an Android

Currently, I am facing a challenge with parsing a substantial JSON response from the server using the Jackson library. The size of the JSON file is approximately 7-8 MB. The error that I encountered while running the code snippet below: ObjectMapper mapp ...

What is the best way to showcase the information stored in Firestore documents on HTML elements?

Currently in the process of designing a website to extract data from my firestore collection and exhibit each document alongside its corresponding fields. Below is the code snippet: <html> <!DOCTYPE html> <html lang="en"> <head> ...

Efficient ways to extract nested JSON data from RESTful JSON web services

Below is a snippet of JSON data that needs to be retrieved in my Java project: {"table":"A","currency":"funt szterling","code":"GBP","rates":[{"no":"1/A/NBP/2012","effectiveDate":"2012-01-02","mid":5.3480}]} I have successfully extracted the data until t ...

Discover the position of characters within a given string

I'm trying to accomplish a task similar to this: If the array [ "a", "b", "c" ] includes any of the characters in the constant word = "abracadabra", I want to retrieve that character along with its position in const word. My attempt so far looks lik ...

Sending a properly formatted string on Postman

My website allows users to answer coding problems. I am looking to store the questions and answers in a mongodb database. However, when testing the routes on my express application, I am encountering difficulties in sending formatted text in the request to ...

What is preventing my accordion from closing completely?

I'm currently working on creating FAQ questions in an accordion format. However, I've encountered an issue where adding padding around the answer section prevents the accordion from closing completely. Removing the padding solves the problem, but ...

Exploring Advanced Querying Methods in Sequelize

I'm trying to display data with a gains value greater than 1, but I'm running into issues when using Postman with the following URL: http://localhost:3000/api/betHistory/winners The result I'm getting is: Executing (default): SELECT `id`, ...

Vue CLI webpack causing image loading issues

What task am I currently working on? I am utilizing the intersection observer API to implement lazy loading functionality. What experiments have I conducted? I have tested the code on a basic HTML page and it functions flawlessly. However, when I incorpo ...