Go through the fields of Vue components iteratively

I've created a Vue component that has over 40 properties which represent a form for editing a business entity. The process flow goes as follows:

  1. Upon mounting, the data is fetched from the server in JSON format and used to initialize the component properties
  2. The data is edited as needed
  3. All the properties are then structured into JSON format and sent back to the server for updating

All the properties in my component have the same names as those in the JSON structure. I'm looking for a way to iterate through the properties in my component and create the JSON structure with just one line of code, instead of manually assigning each property like this:

var data = {
 field1 = this.field1,
 field2 = this.field2,
 field3 = this.field3
 ...
 field40 = this.field40
}

Using TypeScript and vue-class-component, my component code looks something like this:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  template: ...
})
export default class MyComponent extends Vue {
  field1: Number = null;
  field2: Date = null;
  field3: String = null;
  ...
  field40: Number = null;

  mounted() {
    axios.get(..., response => {
      this.field1 = response.data.field1
      this.field2 = response.data.field2
      this.field3 = response.data.field3
      ...
      this.field40 = response.data.field40
    }
  }

  submit() {
    const data = {
      field1 = this.field1,
      field2 = this.field2,
      field3 = this.field3,
      ...
      field40 = this.field40,
    };

    axios.put(..., data);
  } 
}

Answer №1

To improve the reactivity of your fields, consider encapsulating them within a model field in your data:

data:{ model:{}}

Upon mounting, dynamically assign reactive props to your model:

  mounted(){
        for(let item in YOUR_JSON_DATA){
           Vue.set(this.model, item , YOUR_JSON_DATA[item])
        }
   }

When it comes time to submit the form, simply provide your vue model prop:

YOUR_SUBMIT_FUNCTION(JSON.stringify(this.model))

Answer №2

There are two approaches to achieve this.

One method involves creating an array of properties if you have prior knowledge of them (which is considered best practice as it ensures the data property is initialized correctly):

const props=['field1','field2', ...];
export default {
  async mounted(){
     //load the data and ensure only the expected properties are mounted
     //this prevents unexpected behavior.
     const result = await loadMyData();
     for(let prop of props) this[prop]=result[prop];
  }
  data(){
    //instantiate the data object to ensure all properties are reactive
    const data={};
    for(let prop of props) data[prop]=null;
    return data;
  }
  methods:{
    async updateServer(){
       //build the data object to send back to the server then send it.
       const data={};
       for(let prop of props) data[prop]=this[prop];
       await sendUpdate(data);
    }
  }
}

The second approach involves extracting a list of properties when fetching data from the server using Object.keys() and storing them as a data property. You would then need to utilize vm.$set to ensure proper reactivity for all properties, nesting them instead of having them at the root level (refer to the vue docs). Nevertheless, it is assumed that if your view object is meant to react to these properties, you must know them beforehand.

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

Node.js encounters a syntax error

I keep running into a syntax error when trying to parse a JSON file: #!/usr/bin/env node 'use strict'; var pID = require('./pull.json') Here is the specific error message: module.js:453 throw err; ^ SyntaxE ...

Retrieve data from a website's API endpoint using JSON format and display it on a

I came across a URL that displays [{"outlet_group_id": "29","outlet_group_name": "Parco","outlet_group_code": "0000010"}] and I have the following code snippet <script> $(document).ready(function() { $.getJSON('http://sampl.elinkurl.com/ ...

Creating a Vue.js component with dynamic data

Recently, I started working with Vue.js and have been experimenting with it for a few days. One of the challenges I'm facing is trying to dynamically add a new div element with text input every time the enter button is pressed. I would greatly appreci ...

Retrieve an array containing a single item from a JSON using ObjectMapper

I'm currently working with a JSON object, ObjectMapper, and Realm in my project. The JSON structure looks like this: { "result": [ { "id": 20, "types": [ "now" ], "url": "/nl/whereto/ezrhgerigerg", "categor ...

I'm curious about why the value of my variable in service.ts keeps changing whenever the page is refreshed?

Below is my Angular service.ts file code. It is used to store the login status. import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) e ...

How to Retrieve Data from a JSON Object in AngularJS Using $http.get

I am attempting to access the JSON object generated by the Google API. function getMarvelHeroes() { return $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA') .then(getM ...

Error message "Mismatched types: expected Path! but found Context" in Android file verification issue

I'm currently implementing local JSON storage in an app I'm working on. While I've used this method of JSON storage before, I haven't encountered these specific errors: Type mismatch: inferred type is Context but Path! was expected and ...

There was an issue in the v-on handler that resulted in an error: "TypeError: The property '$createElement' cannot be read because it is undefined."

I am encountering an issue with some basic input/output code. The task at hand is to receive input in Newick format and use it to create a tree. However, I am struggling to even receive the input correctly. Below is the HTML code snippet I am using: ...

Obtain accurate dispatch type by leveraging ConnectedProps in conjunction with redux-thunk

Currently, I am utilizing Redux-Toolkit and Typescript. Specifically, my goal is to implement ConnectedProps as recommended in the redux documentation. However, it appears that the dispatch type is not recognized correctly (it is identified as a normal Dis ...

Enhancing the todolist application with an edit feature

Currently, I am in the process of developing a to-do list application. I am trying to incorporate an edit function into the app, similar to what is shown in the image below. Initially, I attempted to pass only this.item.name from the child component (lis ...

Try out NextJS API middleware by running tests with Jest

I have a middleware setup in my NextJS API route, located at /src/middleware/validateData/index.ts. It's used to validate request data using a schema. import { NextApiRequest, NextApiResponse } from 'next'; import schema from './schema ...

The downloaded zip file appears to be corrupt and cannot be opened

As a newcomer to TypeScript, I embarked on creating a simple function to download a zip file. This is the code I've managed to put together: import fs from 'fs'; import https from 'https'; export function handler(): void { https ...

"Is it possible to load the jQuery dform plugin from a JSON file

I have been using the JQuery dForm plugin to construct a form and it has been functioning well with the provided code snippet: $("#myform").dform({ "action" : "index.html", "method" : "get", "html" : [ ...

Issue with JQuery Promise: fail() being invoked before promise resolution

In my TypeScript code, I encountered a peculiar issue with a jQuery promise. The fail() function is being executed immediately, logging an error message to the console, despite the promise resolving successfully afterwards. Here is the code snippet: ...

The functionality of the Ionic 4 app differs from that of an Electron app

I've encountered an issue with my Ionic 4 capacitor app. While it functions properly on Android studio, I'm having trouble getting it to work on Electron. Any ideas on how to resolve this? Here are the steps I took to convert it to Electron: np ...

Is there a different method to retrieve the Circle object found within a JSON using Fabric JS?

Having an issue fetching JSON data from a canvas using FabricJS. The image and rectangle types are being fetched correctly, but there seems to be an issue with circles. The circle appears broken - the controls show up, but the stroke is not visible. Here ...

Converting JSON into a Python Dataframe

Can someone assist me, please? I have a JSON dataset that I am trying to convert into a Python DataFrame. Here is the JSON: I also want to save it to an Excel file. Thank you in advance! data = {'2': {'groupNo': '29', ...

What is the best way to change the name of an imported variable currently named `await` to avoid conflicting with other variables?

Here is the given code snippet: import * as fs from 'fs'; import {promises as fsPromises} from 'fs'; // ... // Reading the file without encoding to access raw buffer. const { bytesRead, buffer as fileBuffer } = await fsPromises.read( ...

Creating a map-like scrolling feature for a full-sized image, allowing both horizontal and vertical movement

My goal is to create an infographic image that can be scrolled horizontally and vertically, zoomed in or out, and where I can add markers just like Google Maps. I attempted the solution of using two scroll views as suggested here: https://github.com/faceb ...

Saving the titles and states of checkboxes in JSON format

My approach involves storing checkboxes title and state as a JSON object with a JSONArray of JSONObject containing these values. I initially attempted to store them in two separate JSONArrays - one for titles and another for states. However, I struggled t ...