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

Is it possible that using npm link could be the root cause of the "module not

As I delve into understanding how to utilize TypeScript modules in plain JavaScript projects, it appears that I am facing a limitation when it comes to using npm linked modules. Specifically, I can successfully use a module that is npm-linked, such as &apo ...

What methods can be used to identify the presence of a scrollbar in an

Currently, I am facing an issue with my SAPUI5 app. In the app, I have a table that extends beyond the screen. To allow users to navigate back to the top of the table, I have added a button. However, I only want this button to be displayed when the table g ...

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Track your status with jQuery technology

I have a link: <a href="/test/number/3/phone/0">33df</a> Is there a way to determine if the words 'number' and 'phone' are present in this link? I am looking for a function similar to: check('number', ' ...

Updating the src of an iframe and adding an onclick event to a link using JavaScript

Looking to design a page that accommodates both login and sign up functionalities by dynamically updating the src of an iframe. In the navigation bar, there is: <li id="change"><a onclick="sign()">Sign up</a></li> And within the ...

Using the innerHTML property to place an Img tag within a div element

I'm facing an issue with including multiple tags within a div using innerHTML. To better illustrate my problem, here's an example: var y = "jack.jpg"; var x = "Jack"; var f = "Hello world!"; document.getElementById("maindDiv").innerHTML += "< ...

Vue emitting events only once across multiple components

Incorporating Vue into my webpage has been a game changer, especially when utilizing eventBus to seamlessly pass data between components. Some burning questions I have are: Is passing data with eventBus between sibling components considered a bad prac ...

Retrieve the index of the item that has been selected in a dropdown list

<select ng-click="getIndex($index)" size="14" ng-model="playlist.fileSelected" ng-options="saveFile for saveFile in playlist.playlist"></select> When I try to access $index, it shows up as undefined. Is there a way to retrieve the index of the ...

The negation functionality in the visible binding of Knockout.js is not functioning properly

I'm having trouble using the visible data binding with a negation and it's not functioning as expected. I've come across various posts on stackoverflow suggesting that the NOT binding should be used as an expression. However, in my scenario, ...

Javascript Using Promise to Await Ajax Content Loading

As a newcomer to JavaScript, I am exploring ways to traverse a DOM that utilizes Checkboxes for filtering results and displays them through Ajax. The checkboxes are organized in 4 levels: Grand Parent Parent Child Grand Child My goal is ...

What is the best way to deliver an HTTP request from the controller to my Ajax function?

Is there a way to send HTTP OK and error responses from the controller to my AJAX request? For example, using HttpStatusCode.OK and HttpStatusCode.BadRequest. When I inspect in my browser it shows impresion.js 304 not modified. $(document).ready(functi ...

Exploring the features of NodeJS, diving into the world of mapping,

Currently, I am working in a Node.js environment and dealing with an array of IDs. My goal is to filter these IDs based on the response of another API call. Essentially, I need to check if each ID meets certain criteria specified by this external API. Whi ...

Is the Packery image grid only functional when the background image is specified in CSS and not in JavaScript? Perhaps we need to look into using Await/Sem

I've successfully implemented a packery image grid that is responsive and functional when the background image in the .item-content section is defined in the CSS file: http://codepen.io/anon/pen/eJdapq .item-content { width: 100%; height: 100%; ...

Prompting the website to 'refresh' and return to the beginning of the page

My website's functionality is closely tied to the user's position on the page. Different features are triggered once specific distances are reached. I am seeking a way for users to automatically return to the top of the page upon page reload. Cu ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

Automate the process of saving information to Google Sheets using Google AppScript

I have a Sheet named 'Automatic' where I've imported a set of data using IMPORTXML. My goal is to update this data list daily at the same time to create a database with various stock quotes over time. Is there a way to accomplish this usin ...

Tips for integrating Chart.js into my AngularJS application?

I am a beginner with AngularJS and I'm currently developing an application on Ubuntu. While trying to add Chart.js using npm install chart.js, an error is being displayed as follows. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Condense categories

Hello there, I'm currently working on a table that contains different groups, and I am trying to figure out how to collapse categories within my table. Check out the Plunker here This is the HTML code snippet I am using: <table border=1> ...

Implement a versatile Bootstrap 5 carousel featuring numerous sliders

Is it possible to create a Bootstrap 5 carousel with six items displaying at a time instead of three? I tried changing the value in the JS code, but it didn't work. Can you correct my code so that it displays six items at a time and can be variable la ...