Vue: Struggling to render JavaScript Map containing keys and values using v-for :key

I have an example Json data like so:

{
   "data":{
      "1":{
         "color":"red",
         "size":"big"
      },
      "2":{
         "color":"red",
         "size":"big"
      },
      "3":{
         "color":"red",
         "size":"big"
      },
      "4":{
         "color":"red",
         "size":"big"
      },
      "5":{
         "color":"red",
         "size":"big"
      }
   }
}

My attempt was to display only the numbers 1, 2, 3, 5 by using this code:

<div v-for = "pos in this.breakdown" :key = "pos">
            <p>{{pos}}</p>
</div>

Unfortunately, it ended up showing the values instead of just the numbers:

{ "color": "red", "size": "big" }

{ "color": "red", "size": "big" }

{ "color": "red", "size": "big" }

{ "color": "red", "size": "big" }

{ "color": "red", "size": "big" }

After converting it into a Javascript's Map of Maps, and trying to display it, nothing showed up as expected:

function jsonToMap(jsonString)  {
    var jsonObject = JSON.parse(jsonString);
    var dataObject = jsonObject.data;
    var dataMap = new Map(Object.entries(dataObject));
    var resultMap = new Map();
    for (const pos of dataMap.keys())  {
        console.log(pos);
        var posMap = new Map(Object.entries(dataMap.get(pos)));
        resultMap.set(pos, posMap);
    }

    console.log("done!");
    return resultMap;
}
<div v-for = "number in this.breakdownTable" :key = "number">
  <p>Number: {{number}}</p>

  <div v-for = "pair in this.breakdownTable" :key = "pair.number">
     <p>{{pair}} = {{this.breakdownTable.get(number).get(pair)}}</p>
  </div>
</div>

Acknowledging Adri1's contribution, I modified my code to this successful version:


        <div v-for="(obj, pos) in this.breakdown" :key="pos">
            <p>{{ pos }}: </p>

            <div v-for = "(obj2, pos2) in obj" :key="pos2">
                <p>{{obj2}} = {{pos2}}</p>
            </div>
        </div>

This modification produced the desired output:

1:

red = color

big = size

2:

red = color

big = size

3:

red = color

big = size

4:

red = color

big = size

5:

red = color

big = size

Answer №1

Utilizing a v-for loop allows you to access the index of the current item being iterated over:

"data": {
  "items": [
    'item A',
    'item B',
    'item C'
  ]
}
<div v-for = "(item, index) in items">
   {{ index }} : {{ item }}
</div>

Output:

0 : item A 
1 : item B 
2 : item C

Now customized for your scenario:

Dealing with unknown object indexes

<div v-for="(obj, pos) in this.breakdown" :key="pos">
    <p>{{ pos }}: </p>

    <div v-for="(obj2, pos2) in obj" :key="pos2">
        <p>{{ obj2 }} = {{ pos2 }}</p>
    </div>
</div>

Explore more v-for options in the official documentation: https://v2.vuejs.org/v2/guide/list.html

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

Display numerous occurrences of a certain class by utilizing a different class

I'm currently in the process of creating a board game similar to Ludo, which requires a grid of 13x13 squares. I've created a Box class that successfully renders a single square button. Here's the code: class Box extends React.Component{ r ...

What is the best way to verify that a JSON key contains only distinct values within a JSON document using JavaScript?

I'm working with a JSON file structure that looks something like this: "fields": { "asset": { "values": [{ "asset": { "id": "Info_text", "type": "text", "value": "ABCD" } ...

using ng-class or ng-style for displaying error messages when validating a text area content

I'm curious about the most effective "angular" method for changing the character count style for validation purposes. I have a text area with a 250-character limit. Instead of restricting users to exactly 250 characters, we want to allow them to excee ...

JavaScript personalized video controls. Silence the video by manipulating the input range element

As a newcomer to javascript, I am working on creating custom video controls using js. One issue I am facing is with a span element that contains a mute/unmute icon. When I hover over this span element, a child element appears with an input range bar for ad ...

JavaScript error: Undefined variable or function

I'm facing an issue with the following code. When I position the brace in different places, I encounter errors like "var not defined" or "function not defined". My goal is to convert an array into a string so that I can analyze the data and decide how ...

Inquiries on VueJS Efficiency

Currently, I am developing a browser extension utilizing Vue Cli with Vue Bootstrap. I have taken steps to optimize my Vue Bootstrap imports by loading only the necessary components and icons for the project. Despite having lazy loaded route components, I ...

Switching Vue.js from the standalone build to the runtime-only build midway through a project?

Opted for the runtime-only version of Vue.js for a new project. I came across in the documentation that to switch to the standalone version, one must include an alias in webpack like this: resolve: { alias: { 'vue$': 'vue/dist/vue.js& ...

Iterating through each data attribute using a jQuery each loop

I've encountered an issue with resetting data attributes post-animation and have been attempting to implement a method found on answer 2 of a related thread. I'm a bit stuck on what might be causing the problem. It should theoretically be possib ...

vue-chartjs is experiencing difficulties when it comes to showing the labels and datasets

I'm having an issue with my line-chart. The data from the api/controller isn't showing up on the chart, even though the response contains all the data. https://i.stack.imgur.com/PWZxZ.png As shown in the image, the line-chart is empty but the r ...

How to dynamically watch elements in an array using Vue.js whenever they change

I am currently developing a text editor that includes fields for name and address. <ckeditor :editor="editor" v-model="data[index].name"> <ckeditor :editor="editor" v-model="data[index].address.1"> <ck ...

Exploring Angular 4's Capabilities: Navigating a Multi-Dimensional Array

I am currently working with a multi-dimensional array that has two keys, and it is structured as follows: user: any = {}; // The index is incremented within a for loop to add values to the user object (this part is functioning correctly) this.user[index++ ...

The preflight request for CORS failed the access control check due to not receiving an HTTP ok status

How can I resolve this issue? Backend: ASP .Net Web APP - API, IIS Frontend: Vue Error: https://i.stack.imgur.com/QG1Yw.png https://i.stack.imgur.com/3tKh7.png Fiddler: https://i.stack.imgur.com/diN08.jpg web.config: <httpProtocol> <cus ...

The error message "SharedArrayBuffer is not defined" occurred when attempting to utilize ffmpeg.wasm

<!DOCTYPE html> <html> <head> <title>TikTok Live Downloader</title> </head> <body> <h1>TikTok Live Downloader</h1> <label for="username">Username:</label> ...

In React production, the use of .map as a function is unavailable

While my express react app build runs smoothly locally with the map function, the transition to production triggers an error stating that 'map' is not a function. The error specifically points to the line declaring 'let returnlist'. Be ...

Adjusting the size of content tags depending on their popularity

Currently, I am working on setting up a basic tagging system by following the database structure provided in this Stack Overflow post. My goal is to create a single page that showcases all the tags, with each tag being visually scaled based on its popular ...

Access environmental variables within Next.js middleware

Within my nextjs project, I have declared variables in both the .env and next.conf.js files. The code snippet from the next.conf.js file looks like this: module.exports = { env: { NEXT_PUBLIC_JWT_SECRET: "...", }, publicRuntimeConfig: { ...

Relentless reloading problems with Ajax on Internet Explorer 7

Currently, I am facing an issue with my AJAX implementation along with executing some JavaScript/jQuery code. The problem is specific to IE7 as it keeps reloading the content repeatedly without stopping, while other browsers work fine. I have tried a coup ...

Sending a POST Request between two websites using JavaScript

I am facing an issue where I need to send a POST request from an application on SERVER1 to another application running on SERVER2. SERVER1: <form name="submitForm" method="POST" action="http://SERVER2:4120/download_item/&qu ...

What sets apart importing components in computed from importing components in dynamic import in Vue.js?

Imagine there are 4 components available on a page or within a component, and the user can utilize them based on their selection by toggling between Input, Image, Video, or Vudio components. There are two ways to lazily load these components: 1) <temp ...

Is there a way to set the same href link for the active class in the navbar using bootstrap-vue?

I am currently utilizing this navbar. It works fine when the href links are unique, but I encounter an issue when two pages share the same link - the active class is applied to both list items with that link in the manner I have written. Vue.component(& ...