Tips for avoiding the 'Duplicate keys detected' error when using a v-for loop in Vue.js

In my most recent project, I utilized Nuxt.Js along with Vuetify.js as the UI framework. The language I used was TypeScript. As part of this project, I attempted to create the image below using arrays.

https://i.sstatic.net/t1Xsc.jpg

    export const dummyData = [
    {
        id: "1",
        name: "a",
        sub: [
            {
                id: "1#1",
                name: "b",
                sub_sub: [
                    { id: "1#1#1", name: "b-a" },
                    { id: "1#1#2", name: "b-b" },
                ]
            },
            {
                id: "1#2",
                name: "c",
                sub_sub: [
                    { id: "1#2#1", name: "c-a" },
                ]
            },
        ]
    },
    {
        id: "2",
        name: "d",
        sub: [
            {
                id: "2#1",
                name: "e",
                sub_sub: [
                    { id: "1#2#1", name: "e-a" },
                ]
            }
        ]
    },
]

I believed I had successfully created a data table using the code snippet provided below.

    <template>
  <div>
    <v-simple-table dense>
      <thead>
        <tr>
          <th class="blue lighten-5">name</th>
          <th class="blue lighten-5">sub_name</th>
          <th class="blue lighten-5">sub_sub_name</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="item in items">
          <template v-for="(subitem, iSub) in item.sub">
          <tr v-for="(sub_subitem, iSub_sub) in subitem.sub_sub" :key="sub_subitem.id">
            <td v-if="iSub === 0 & iSub_sub === 0" :rowspan="rowSpanCalc(item)">
              {{ item.name }}
            </td>
            <td v-if="iSub_sub === 0" :rowspan="subitem.sub_sub.length">
              {{ subitem.name }}
            </td>
            <td>{{ sub_subitem.name }}</td>
          </tr>
          </template>
        </template>
      </tbody>
    </v-simple-table>
  </div>
</template>
.
.
.
.
 

After encountering some issues and seeking help on StackOverflow, I thought everything was working fine until I received feedback from my client reporting an error like the one shown below:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Duplicate keys detected: '1#2#1'. This may cause an update error.

The issue seems to be related to the usage of 'v-bind:key' in my code. Even though I tried to ensure each key is unique, the error still occurred. Any suggestions on how to resolve this problem?

Answer №1

Each key must be unique and should consist of a combination of the respective indexes from all three loops

<template v -for="(item,item_index) in items">
    <template v -for="(subitem, iSub) in item.sub">
      <tr
        v
        -for="(sub_subitem, iSub_sub) in subitem.sub_sub"
        :
        key="`${item_index}-${iSub_sub}-${sub_subitem.id}`"
      >
        <td v -if="iSub === 0 & iSub_sub === 0" : rowspan="rowSpanCalc(item)">
          {{ item.name }}
        </td>
        <td v -if="iSub_sub === 0" : rowspan="subitem.sub_sub.length">
          {{ subitem.name }}
        </td>
        <td>{{ sub_subitem.name }}</td>
      </tr>
    </template>
</template>

Answer №2

It's pretty much spot on with what it promises:

[Vue warn]: Duplicate keys detected: '1#2#1'. This could lead to an update issue.

Your data is using "1#2#1" as an id for multiple items.

To resolve the error, ensure your data has unique ids like this:

export const sampleData = [
    {
        id: "1",
        name: "a",
        sub: [
            {
                id: "1#1",
                name: "b",
                sub_sub: [
                    { id: "1#1#1", name: "b-a" },
                    { id: "1#1#2", name: "b-b" },
                ]
            },
            {
                id: "1#2",
                name: "c",
                sub_sub: [
                    { id: "1#2#1", name: "c-a" },
                ]
            },
        ]
    },
    {
        id: "2",
        name: "d",
        sub: [
            {
                id: "2#1",
                name: "e",
                sub_sub: [
                    // Changed "1#2#1" to "1#2#2"
                    { id: "1#2#2", name: "e-a" },
                ]
            }
        ]
    },
]

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

Strategies for avoiding interruption of the dragenter event while dragging over a nested element

I'm currently developing a personalized drop zone feature. Below is the HTML code snippet: <template>   <div class="dropzone"     @drop.prevent="dropFileHandler"     @dragover.prevent="dragOverHandler" ...

xhttp.load path for server-side module

I'm currently working on developing a node package and in my JavaScript code, I have the following: const calcHtml = './calc.html'; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { ...

What is the process for generating an array of objects using JavaScript?

I am struggling to create an array of objects using JavaScript and facing errors with new lines added where I need to split the messages and collect row numbers. The row numbers should be comma-separated if it is a repetitive error message. I found a solu ...

Using JavaScript to Include CSS File or CSS Code

Greetings! I am curious about replicating the functionality of this PHP code in JavaScript: <?php if (strpos($_SERVER["HTTP_USER_AGENT"], 'Chrome') == true) { echo "<style>h1 { color: red; }</style>"; } ?> ...

The Javascript Navbar is malfunctioning on Firefox

Currently, I am working on a horizontal menu that includes submenus. My goal is to use Javascript to display the submenu when a user hovers over the parent menu. I created a JSFiddle example, which seems to be experiencing issues in FireFox! However, it w ...

Is it possible to programmatically click a plotly mode bar button using JavaScript in a Shiny app?

After some research, I've discovered that in order to achieve my goal, I need to incorporate shinyjs and extendShinyjs. Here's what I have implemented so far: In the ui.R file, outside of the ui function: js_reset_axes <- "shinyjs.reset_axes ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

Guide on Postman: Tracking the number of occurrences for a particular object in a JSON reply

I am just starting out with JSON and Postman. I have a simple task in mind. I have set up a GET request that will return a JSON response like the one below. In this example, I want to extract the count of all "IsArchived" attributes in the response. The ...

Creating a personalized Angular component from an external library that can be activated with the "enter" key

The issue at hand Summary: I am encountering a problem with an angular component that is not clickable using the "Enter" key. I have developed a library using stencil that contains and produces various angular components to be utilized across multiple ap ...

React URL displaying query

I am currently developing a React app using HashRouter. Within the app, there is a form with inputs where, after the user submits data, some of the information ends up in the URL like this: http://localhost:3000/?State=Alabama#/profile However, it should ...

Bootstrap Carousel is unable to display any items as the count returns zero

I'm having trouble determining the total number of items in a Bootstrap carousel, as my code consistently returns 0: var totalItems = $('.carousel-item').length; The data-ride attribute is specified in the parent div: <div id="carous ...

Upon clicking the Submit button in Selenium Webdriver (Java), the passwords field is cleared and the flow is halted

I am encountering a problem in IE11 while using Selenium in Java. After inputting the username and password into the fields, when I click the Submit button, the password field is cleared and the automation process cannot proceed. Even though it works fine ...

Guide to showing user input upon button click using Vue?

I've been researching text fields but I'm having trouble understanding it.. I'd like to input a name and age, and then after clicking the "add" button, I want to see the name and age displayed below. What is the most efficient or optimal way ...

Guide on importing a markdown file (.md) into a TypeScript project

I've been attempting to import readme files in TypeScript, but I keep encountering the error message "module not found." Here is my TypeScript code: import * as readme from "./README.md"; // I'm receiving an error saying module not found I als ...

Setting up a function in React to utilize an image stored in state

I have a function in my react component for image classification that retrieves the image from the img tag using document.getElementById: const img = document.getElementById('animal_image');. The image uploaded via the file input updates the sta ...

I am unable to input just one numerical value into my function

I am encountering an issue with my function that calls another function. The problem arises when inputting single numbers in the prompt; I have to append a letter like (a1, a2, a3) for it to function correctly. The function "PrintSelectedToPDF" works smoo ...

Tips for emphasizing matches within a string using JSX

I've implemented a custom autocomplete feature that suggests options based on user input. I want to highlight the characters in the suggestions list that match the input value. For example, if the suggestion list includes "alligator", "lima", and "li ...

Make all Bootstrap cards in uniform size by stretching them

I've been working on creating a rotating table of cards using owl-carousel and bootstrap for my webpage, but I'm facing an issue with card heights not being uniform. I want all the cards to have the same height for a more streamlined and professi ...

Terminate all dormant MySQL pool connections using Node.js

In my project involving node.js and connection pooling, I have noticed that despite releasing connections after each query as shown below: return new Promise((resolve, reject) => { sql.getConnection(function (err, conn) { if (err) { ...

Issues with AngularJS functionality have been noticed in Chrome browsers on both Mac and Windows platforms, with Safari being

As I begin my journey into learning AngularJS, I encountered an unusual issue. The code snippet below is taken from an online tutorial on Github. Interestingly, the code functions flawlessly on Safari (MAC) but fails to load on Chrome. The same problem p ...