Mastering the map() function in Vue.js 2

As I start learning vue.js, I am facing some challenges. I need to implement a dictionary analog in JavaScript, known as a map. However, I'm unsure of where to define it. The map should be utilized in both the checkDevices() method and within the HTML code.

P.S. Please excuse any language errors in my English

export default {
    data: () => ({
   }),
   devicesList: new Map(
    "varNameOne", false,
    "varNameTwo", false,
    "varNameThree", false,
    ),
    methods: {
        async checkDevices () {
            let response = await axios.get(`/some/api`)
            console.log("res.data: ", response.data);

            devicesList.forEach((values, keys) => {
            console.log("Key: ", keys, "Value: ", values);
            })
        }
    }
}

I have attempted to define it before export default like this: let devicesList = new Map(...);, but unfortunately, it did not work as expected.

When using axios.get(`/some/api`), I receive a server response with data (response.data):

device1: true
device2: false
device3: true 

I need to extract this data from the response in key-value pairs for UI presentation such as:

  • device1 connected
  • device2 disconnected
  • device3 connected

Answer №1

To properly handle the Axios response, you'll need to make adjustments in the checkDevices function to ensure it matches the key values. It's not necessary to use map before export default; instead, you can perform this task within the mounted function.

export default {
    data:function(){
        return {
            devicesList:[]
        }
    },
    mounted:function(){
        this.devicesList = new Map();
        this.devicesList.set('device1', false);
        this.devicesList.set('device2', false);
        this.devicesList.set('device3', false);
    },
    methods: {
        async checkDevices () {
            let response = await axios.get(`/some/api`)
            console.log("res.data: ", response.data);

            devicesList.forEach((values, keys) => {
                console.log("Key: ", keys, "Value: ", values);
                //Remember to utilize YOUR RESPONSE.data to update the device List here
            })
        }
    }
}

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

Expand the image to fill the entirety of the viewing area

Check out my development website. Whenever you click on an image, a photo slider (using photoswipe) pops up. Is there any way to have the image fill the entire viewport? I attempted using height: 100vh, width: auto, but it didn't work. https://i.ssta ...

What is the best way to extract user input from a bootstrap search bar and integrate it into an ajax request to fetch information?

I am currently utilizing HTML, Javascript, and bootstrap to develop a web application. However, I have encountered an obstacle. When using the code document.getElementById("input here"), it only returned an array of 0. My goal is to retrieve data from an A ...

Getting image blob data with Cropper Js in a Laravel controllerNeed help on how to get image blob data

I've been working with Cropper.js and Laravel. I managed to crop an image, put it into FormData, and send it to the Laravel controller using jQuery Ajax. However, I encountered a problem where I am not receiving any data in the controller, only an err ...

Verifying a checkbox selection within an Autocomplete feature using MUI

[ { label: 'First', checked: false }, { label: 'Second', checked: true } ] Here is a brief example of how the data may be structured. I am utilizing Material UI's Autocomplete feature to enable searching based on labels. Thes ...

Generate a graph by utilizing $getJSON and ChartJS

I am currently working on creating a bar chart using ChartJS and a JSON file. The data format is provided below, with each object containing information about the station name and arrival time. My goal is to populate an array where the x-axis represents St ...

JavaScript - The AJAX response is consistently after being undefined

I am encountering an issue with the following functions: function get_non_authorized_bulk_edit_option_values() { var modificable_column_names = get_write_user_values(); alert(modificable_column_names); } The above function is calling this ...

How to transform multi-dimensional arrays to JSON format using JavaScript (and maybe jQuery)

Currently facing a Javascript dilemma where data storage is essential in the following format: MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..) The main array consists of ...

Experiencing an issue in Test Cafe when attempting to click on an invisible link using the Client Function

I need to find a way to click on an invisible button in HTML. I attempted to use ClientFunction, however I encountered an error related to the element. import { Selector,ClientFunction } from 'testcafe'; fixture('Clicking Invisible link&apo ...

Passing parameters as an array in Angular can be done by using the format: ?category[]=1&category[]=2&category[]=3,

Struggling to send an array using the $http.get() method in AngularJS. Here's my current approach: $http.get('/events.json', {params: {category_id: [1,2]}}); While I anticipate the request to be sent as /events.json?category_id[]=1&cat ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

Feeling uncertain about Node, NPM, Bower, and how to set them up for Bootstrap?

Looking to expand my knowledge in web development, I have a solid understanding of HTML, JS, CSS, and server-side programming. However, the concepts of Nodejs, npm, and Bower are still unclear to me. In order to begin a new project, I created a designated ...

Utilize Angular to transform a standard text string within a JSON object into a properly formatted URL

Welcome to my first Stack Overflow question! I usually find the answers I need on my own, but this time I could use some guidance as I delve into Angular. I have a directive that pulls the name and URL from a JSON object and generates HTML with the name a ...

How can a jQuery fadeTo Effect be timed?

Presently, I am utilizing jQuery's fadeTo function to gradually fade in a div. Nevertheless, I am encountering a slight timing issue. I have an Animated GIF file that I wish to synchronize with the jQuery fadeTo effect. I have tried using window.onlo ...

Converting Blob to Base64 using javascript

I've managed to successfully convert my base64 (DATA_URI) image into a blob, but I'm facing issues with reverting it back. Here's what my base64 to blob code looks like for better understanding. Check out this link. b64toBlob(b64Data, cont ...

Show fixed div at specific height

Is there a way to have a fixed title in a DIV that only displays once the user scrolls to the relevant section on the website? I'm looking for a solution where the DIV is hidden until the section is reached during scrolling. ...

Tips for integrating tooltips in a dynamic highcharts chart

This image shows the desired final output View Highcharts here and I am looking to merge the date and stock value in a single tooltip, how can this be achieved? highcharts ...

Is there a way to fully break out of a .forEach loop that's nested within a function?

Here is the method I am currently working with: wordFormDirty = (): boolean => { var self = this; angular.forEach(self.word.wordForms, function (wf, key) { var wordFormNgForm = 'wordFormNgForm_' + wf.wordFormId if ...

What does the HTML and JS code look like when using Next.Js?

Here's an illustration of the desired result: codepen.io/j0be/pen/jWGVvV How can I implement this HTML and JS in Next.js? I am looking to customize this code using TypeScript and SCSS in Next.js. However, I am unsure about how to convert the HTML an ...

Experiencing a JSONP issue with an 'Access-Control-Allow-Origin' error

When working with PHP, I often use the following code to echo JSONP formatted data: echo $_GET['callback'] . '('.json_encode($arr).')'; In my AngularJS (JavaScript) code, I make a GET request like this: $http.get('http ...

Tips for transforming every element of an array into its own array using JavaScript or Loadash

Hello, I have an array that looks like this. I am attempting to convert each element into its own array. I tried using lodash's chunk function but was unsuccessful. [ 'Product 1', 'Product 2', 'Product 3', 'Product ...