How to iterate through the elements of an object within an array using Vue.js and TypeScript

There was an issue with rendering the form due to a TypeError: Cannot read properties of undefined (reading '0'). This error occurred at line 190 in the code for form1.vue. The error is also caught as a promise rejection.

Error Occurred

<input
 type="text"
 class="form-control"
 v-model="data['item3'][0].item1"
/>

The data structure is expected to have item3 as an array containing objects, and trying to access the first object within it has resulted in an error.

vue page data includes:</p>
<pre><code>const data = ref<any>({});

onMounted(() => {
  data.value = props.modelValue;
  if (!data.value['sheetname']) {
    data.value = new E507().data;
    data.value.sheetname = props.sheet.templatename;
  }
  console.log(data.value);
});

Accessing data['item3'][0] directly seems problematic and resulted in binding issues. Perhaps using the optional chaining operator like data['item3']?.[0] could help resolve this problem.

If you are facing difficulties accessing the 0th object in item3, consider checking the validity of the data structure or implementing alternative methods to handle this specific scenario.

Answer №1

Based on the data object you provided, it is recommended to use v-model with item3[0].item1 instead of data['item3'][0].item1

Check out the Live Demo below:

const vm = {
  data() {
    return {
      item3: [{
        item1: 'SSS',
        item2: [{
          item3: '2'
        }],
        item3: '',
        item4: '2',
        item5: '',
        item6: '',
        item7: '',
        item8: '',
        item9: '',
        item10: '1',
        item11: '1',
      }]
    }
  }
}

Vue.createApp(vm).mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.1/vue.global.js"></script>
<div id="app">
  <input
         type="text"
         class="form-control"
         v-model="item3[0].item1"
         />
</div>

Update : If you are using composition API, please note that the previous answer was for Options API. Here is the solution for composition API.

Since the reference is updated in the mounted hook, it may not load before the template render. To fix this issue, add v-if="data.item3" in the input element.

Explore the Demo below:

const { ref, onMounted } = Vue;

const vm = {
setup: function () {
    let data = ref({});
    onMounted(()=>{
      data.value = {
        item3: [{
          item1: 'SSS',
          item2: [{
            item3: '2'
          }],
          item3: '',
          item4: '2',
          item5: '',
          item6: '',
          item7: '',
          item8: '',
          item9: '',
          item10: '1',
          item11: '1'
        }]
      }
    })
    return {
      data
    }    
  }
}

Vue.createApp(vm).mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.1/vue.global.js"></script>
<div id="app">
<input
         v-if="data.item3"
         type="text"
         class="form-control"
         v-model="data['item3'][0].item1"
         />
</div>

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 API key fails to function properly when imported from the .env file, but performs successfully when entered directly

Working with Vite has been quite an experience for my project. I encountered a situation where using my API key directly worked fine, but when trying to import it from .env file, I faced the error message in the console below: {status_code: 7, status_me ...

Troubleshooting Issue: XMLHttpRequest Incompatibility with Internet Explorer

I'm having an issue with the script below. It works fine on Firefox and Chrome but doesn't seem to work on IE. I've tried various solutions, including lowering the security settings on my browser, but it still won't work. function se ...

When a TypeScript merged declaration composition is used with an extended target class, it fails to work properly

I have a TypeScript problem where I need to combine a class that has been extended with a few others. While searching for solutions, I came across an article outlining a pattern that I thought could be helpful: https://www.typescriptlang.org/docs/handbook ...

Locate and embed within a sophisticated JSON structure

I have an object structured as follows: interface Employee { id: number; name: string; parentid: number; level: string; children?: Employee[]; } const Data: Employee[] = [ { id:1, name: 'name1', parentid:0, level: 'L1', children: [ ...

Tips for utilizing browser cache in AJAX requests to prevent loading the refreshed JSON file

It may seem like a strange question, but I'm experiencing an issue with an AJAX call to a JSON file. Both the request and response headers do not indicate to not use cache, and in the browser settings, the Disable cache option is not checked. What mor ...

Tips for incorporating Javascript in an innerHTML inline css situation

I'm just starting to learn about html5 and php. I'm curious about how to incorporate javascript into my existing code. Currently, I have data from a database displayed in an HTML table. My goal is to align the output of the last cell more toward ...

THREE.js : Chart Your Course in the Digital Realm

When I have a moving object controlled by code such as: dx = [not important]; dy = [not important]; dz = [not important]; d = new THREE.Vector3(dx, dy, dz); mesh.postion.add(d); How can I ensure that my mesh is facing the direction it's moving in? I ...

Achieving a function call within a Backbone view in Backbone.js

Is it possible to call the plotPort function from the plotLoc function using this.plotPort() instead of self.plotPort()? It seems to not work for Internet Explorer when using self.plotPort(). As a workaround, I added an event to lLoca upon reset to call ...

Wondering how to go back to the default locale in Next.js?

Within my Next.js application, I have successfully implemented the next-i18next module for multi-language support. The app currently supports two languages: English and Arabic, with English set as the default. To allow users to toggle between languages, I ...

Failed jQuery AJAX request to database with no returned information

I'm really confused about where the issue lies :S The button triggers a function that passes the parameter "sex" and initiates an ajax call to ajax.php, where I execute a MySQL query to retrieve the results and populate different input boxes. When I ...

Data binding in Vue.js seems to be malfunctioning

I'm having trouble with my Vue component creation. I've been using v-show to hide certain elements, but it doesn't seem to be working as intended. The goal is to hide an element when clicked from a list by setting element.visible to false i ...

Apps created with PhoneGap will maintain the original sizing of web pages and not automatically resize for display on Android devices

After successfully porting my web-based tool to Android using PhoneGap from my Github repository, I encountered an issue with the display on Android devices. The app loads up too big for the screen, forcing me to constantly scroll around to see and access ...

How can we minimize the data contained in JSON HTML markup?

https://i.stack.imgur.com/mzuB0.png Currently, I am attempting to find a way to conceal the last 12 digits in the price shown on a button, as it is excessively long. The method I am utilizing involves a JSON api and insertAdjacentHTML markup. This snipp ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

retain focus even after using .blur()

Currently, I am implementing a form submission using AJAX. The form consists of only one input field and the submit button is hidden. My aim is to ensure that when the user hits the enter key, the input field does not lose its focus. Here's the code s ...

Is it best practice to initialize loaded scripts before the JQuery .load callback is called or should it be done after the .ready callback in the loaded script?

When I click a button in my main document, I load the content of a specific div using jQuery: $("#my_div").load(function() { alert("Content Loaded"); }); The loaded content contains a script: <script> alert("Initial Alert from External Script" ...

Error while retrieving reference from mongoDB in NodeJS

I am currently working on a small website that needs to query my local mongodb. Everything works perfectly fine on localhost. That's why I decided to begin with NodeJS. While all JavaScript functions work seamlessly when run separately, I encounter a ...

Using vuex to paginate through firestore data and seamlessly update the state with new information

After taking advice from Tony O'Hagan on Stack Overflow, I integrated the following code to exhibit a paginated query: bindUsers: firestoreAction(({ bindFirestoreRef }) => { return bindFirestoreRef('users', Firebase.firestore().c ...

What is the best way to implement a timer or interval system in React and Next.js that continues running even when the tab is not in focus or the browser is in

I am attempting to create a stopwatch feature using next js. However, I have encountered an unusual issue where the stopwatch does not function correctly when the tab is not focused or when the system goes to sleep or becomes inactive. It appears that the ...

Using Javascript to pass the value of a selected checkbox

I am having an issue with passing a row value to a different function when a user clicks on a checkbox in the last column of a table. The code I have written doesn't seem to be firing as expected. Can anyone help me figure out what might be missing in ...