How to implement a for loop within a Vue.js method

Within Vuejs, I have a method that updates multiple variables based on user selection.

methods: {
  updateChart(){
    this.chart1.series[1].data = [this.$store.state.selectedcities[0].value[1]];
    this.chart1.series[2].data = [this.$store.state.selectedcities[0].value[2]];
    // Update the remaining series with similar pattern...
  }

The current code seems quite verbose. I'm considering using a for loop to iterate through the numbers, even though they are not sequential as indicated by

{1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22}
.

I would like to achieve something like:

methods:{
 updateChart(){
  var n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22];
    for(let i of n){
          this.chart1.series[i].data = [this.$store.state.selectedcities[0].value[i]];
            }
          }
        }

As a newbie in JavaScript, I'm unsure about how to proceed with this approach.

EDIT:

Is it feasible to include a nested forEach loop in this scenario? For instance:

var k = [1, 3, 6];
var n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22];
    n.forEach(i => {
          this.chart[k].series[i].data = [this.$store.state.selectedcities[k].value[i]];
            })

Note the addition of variable k into the formula and the relation of n as a subset of k. This implementation aims to run series of n for each k value.

Answer №1

n must be an array and iterated through using the forEach method as shown below:

 var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]
    n.forEach(i=>{
          this.chart1.series[i].data = [this.$store.state.selectedcities[0].value[i]];
            })

ُEDIT

var m = [1,3,6]
 m.forEach(k=>{
     n.forEach(i=>{
          this.chart[k].series[i].data = 
        [this.$store.state.selectedcities[k].value[i]];
            })

})

Answer №2

To iterate through the array, you can utilize the forEach method.

updateChart() {
    var numbers = [1,3,5,7,8,10,11,13,15];

    numbers.forEach(num => {
        this.chart.series[num].values = [this.$store.cities[0].details[num]];
    });
}

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

Skipping the created hook in Vue Test Utils is a useful feature that allows

Is there a way to skip all the methods called within the created() hook? Instead of: created() { this.getAllocations(); this.getModels(); this.getTeams(); this.getCustodians(); this.getD ...

Guide on navigating to a different page by simply clicking on a row within an HTML table

I am using an MVC application. When a user clicks on a row in the Index page, I want them to be directed to the DetailInfo page. How can this be achieved? This is part of the code in Index.cshtml @for (var item = 0; item < Model.Count; item++ ...

What could be causing the repeated calls to a computed function in vuejs?

In my Vuejs application, I start by fetching initial data and setting it in the store: const app = new Vue({ router, store, mounted: function() { var that = this; $.get("/initial_data/", {}, function(data) { that.$s ...

Export data table from HTML to Excel successfully implemented with C#

I am currently working on an Umbraco website and developing a custom plugin for the backend that allows users to export an Excel worksheet from an HTML table. In order to achieve this functionality, I am utilizing AngularJS along with a C# controller. Belo ...

progressing both forward and backward through every month

I am currently working on a project that involves creating a calendar using JavaScript. I have implemented functionalities where I can navigate back and forth through months, fetching the days within each month. However, I am facing an issue where if I go ...

Troubleshooting: Jquery UI Draggable - Cursor losing track of draggable element

I want to create a draggable popup with Jquery UI functionality, but I'm facing an issue where the cursor does not stay aligned with the popup element when dragged. When dragging the popup element to the left, the mouse cursor goes beyond the div elem ...

What is the process for creating a custom hook in React.js/Next.js?

I encountered a problem while trying to create a hook from my code. Here is the snippet from the hook file: import { useRouter } from "next/router"; const useCurrentPath = () => { const { asPath, locale, defaultLocale } = use ...

Error encountered when referencing iscrollview and iscroll js

Greetings! I am new to the world of JavaScript and jQuery, currently working on developing a phonegap application. As part of my project, I am exploring the implementation of the pull-to-refresh feature using iscroll and iscrollview as demonstrated on & ...

Avoiding Rejected Promise: Warning for Error [ERR_HTTP_HEADERS_SENT] due to Issue with setInterval and Axios.post Error Management

I attempted to address this warning by researching online. Unfortunately, I couldn't find a solution, so I am reaching out with this question. The current warning that I am encountering is: (node:39452) UnhandledPromiseRejectionWarning: Error [ERR_H ...

A guide to sorting an object with integer keys by its values using JavaScript

I am facing an issue with sorting a map by values instead of keys. No matter what I do, it always ends up getting sorted by the keys. On the server side, I have a map that is already sorted. When I send this map to JavaScript using JSON, it gets re-ordere ...

Utilize Django to leverage a JSON file stored within a context variable for use in jQuery

I need to utilize a list in Jquery and integrate it with the Autocomplete jQueryUI widget. The list is small, so creating a new request seems unnecessary. Therefore, I believe using Jsquery's getJSON is also not required. Here is my current setup: ...

What is the process for implementing a decorator pattern using typescript?

I'm on a quest to dynamically create instances of various classes without the need to explicitly define each one. My ultimate goal is to implement the decorator pattern, but I've hit a roadblock in TypeScript due to compilation limitations. Desp ...

Exploring jQuery's parent selector for traversing the DOM

I am currently working with an array that inserts articles into my website. I have a specific requirement where, upon clicking the title (h3), I need to display more information based on the article's index. To achieve this, I believe I should travers ...

Merge JavaScript Functions into a Single Function

I am looking to streamline the following javascript code into a single function by utilizing an array of ids instead of repetitive blocks. Any suggestions on how to achieve this would be greatly appreciated. Currently, in my code, I find myself copying an ...

What could be causing the 'Invalid element type' error to occur in my React Native application?

`import { StyleSheet, Text } from 'react-native'; import { Provider } from 'react-redux'; import { store } from './store'; import { HomeScreen } from './screens/HomeScreen'; import { SafeAreaProvider } from 'rea ...

Using a set formatter in jqGrid within a personalized formatter

Can I incorporate a predefined formatter into a custom formatter? Here is an example using the colModel: colModel: [ ... { name: 'col1', formatter: myFormatter } ... ] Below is the custom formatter function: function myFormatter(cellVal ...

Aligning a div vertically in the center of its parent container

I am trying to vertically align a child element within its parent element <!DOCTYPE html> <html> <head> <title>Test</title> <style type="text/css"> #body { font-family: sans-serif, arial, 'Roboto'; } #outer ...

Showing the date in AngularJSAngularJS can be used to

I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use <span>{{Date.now() | date:'yyyy-MM-dd'}}</span> to display the current date. ...

Toggle the JavaScript on/off switch

I am attempting to create a toggle switch using Javascript, but I am encountering an issue. Regardless of the class change, the click event always triggers on my initial class. Even though my HTML seems to be updating correctly in Firebug, I consistently ...

Get rid of the unnecessary vertical line that is located at the end of the string

I have come across a situation similar to the one demonstrated in this code snippet: http://plnkr.co/edit/eBjenGqgo3nbnmQ7XxF1?p=preview Currently, I am working with AngularJS 1.5.7. The directives used in my input - ( first ) textarea are the same as tho ...