Utilizing the v-for directive to loop through JSON data with unique IDs and linking them to Input components in PrimeVue

In my database, I have a collection of products with a column named attributes that stores property/value pairs in JSON format. Each product can have unique attributes. For instance, one product's attributes could be:

#product1
attributes {
  color: "green",
  size: "small"
}

While another product's attributes might look like this:

#product2
attributes {
  width: "12inches",
  height: "11inches
}

I am currently developing a form to Create, Read, Update, and Delete (CRUD) these products, including their dynamic attributes. The current setup is as follows:

https://i.sstatic.net/HBXIH.png

I'm using PrimeVue framework to build this application and form, and I'm attempting to bind these property/value pairs to some PrimeVue components (InputText). These components require a Vue data property to be bound using the v-model directive on the input fields. The code snippet for this is shown below:

<InputText v-model="product.attribute_property" id="attribute_property" placeholder="key" />
  <span class="p-inputgroup-addon"> : </span>
<InputText v-model="product.attribute_value" id="attribute_value" placeholder="value" />

The corresponding Vue data is structured like this:

export default {
    data() {
        return {
          product {
            
          }
      }
    }
}

Upon parsing the JSON retrieved from the database table, the output appears in the Vue developer tools window as shown here: https://i.sstatic.net/HWWeB.png

My initial plan was to use v-for to iterate through the properties and values dynamically and create each Input field accordingly, but this approach did not work. It seems that my lack of understanding on how these functionalities interact is hindering progress. I attempted this method:

<div v-for="(value, key) in attributes" :key="key">
  <div class="p-inputgroup">
    <InputText v-model="key" id="attributes_key" placeholder="key" />
    <span class="p-inputgroup-addon">&nbsp;:&nbsp;</span>
    <InputText v-model="value" id="attributes_value" placeholder="value" />
  </div>
</div>

However, an error stating '

'v-model' directives cannot update the iteration variable 'key' itself
' was thrown. It is apparent that my method of iterating through the JSON data is incorrect, but I am unsure of the correct or most efficient way to handle it. Ultimately, my objective is to bind these properties to the input fields and generate dynamic attributes for the products. I just need guidance on utilizing v-for properly to access the property/value pairs. Any help would be greatly appreciated.

Answer №1

Expanding upon the feedback:

According to the error message, it is not possible to directly modify the key. Instead, you should extract the key-value pairs into a new array of objects and make changes to this new array. After editing, you can reconstruct the products based on the updated array.

Extract the key-value pairs into a new array of objects,

..
data() {
return {
  attributes: {
    type: "shirt",
    brand: "Nike",
  },
  newAttributes: [],
 };
},

//after mounting:
mounted: function () {
 let attributes = this.attributes;
 let keys = Object.keys(attributes);
 let newValues = [];
 keys.forEach((attrKey, i) => {
   let obj = {};
   obj["key"] = attributes[attrKey];
   obj["val"] = attrKey;
   newValues.push(obj);
 });
 this.newAttributes = newValues;
},

Iterate through the newAttributes array and update it. Then, reconstruct the products array, perhaps within a computed property

computed: {
 reFormattedAttributes: function () {
   let attributes = this.newAttributes;
   let formatted = {};
   Array.from(attributes).forEach((attribute) => {
     formatted[attribute["key"]] = attribute["val"];
   });
   return formatted;
 },
},

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

Having difficulty creating JSON data following retrieval of rows by alias in MySQL

I am encountering an issue while trying to fetch rows from two tables using a JOIN and aliases. The problem arises when I attempt to convert the fetched rows into JSON data and assign them to a JSON array. Below is the code snippet: $personal = $db->p ...

Facing an issue where WordPress AJAX is not showing the expected content

Currently, I am in the process of creating a WordPress website that will feature an initial display of two rows of images. Upon clicking a button, two more rows should dynamically appear. There are four key files involved in this project: case-study-ca ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

Unusual express middleware usage in NodeJS

app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.get('/2',function(req,res){ console.log('/2'); res.end() ...

Developing a personalized loop in handlebars templates

Just starting out with NodeJS and ExpressJS. I'm looking to customize a for loop in order to iterate through data from NodeJS using an index, akin to a non-traditional for loop. Take a look at the code snippet below, extracted from NodeJS, where I re ...

The functionality of the web application is not supported in Multi-Device-Hybrid-Apps format

I am encountering an issue with my app that functions perfectly as a typical web app, but fails to work properly when converted into a Multi-Device-Hybrid-App format. The problematic sections are indicated in a screenshot of the app. Below is my complete c ...

Conceal location labels in maps provided by tilehosting.com

I am currently in the initial stages of developing a maps web application and I want to incorporate maps from tilehosting.com along with the leaflet library (leafletjs.com). Overall, it seems to be working fine, but I'm struggling with hiding the def ...

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

Keep an eye on the audio time changes in Vue!

I am working on a project where I have an audio file that plays songs. Currently, I am developing a slider that corresponds to the length and current time of the songs. However, I am facing a challenge as I cannot use player.currentTime in the watch compon ...

Creating a QueryBuilder using JSON DSL with the Java API in ElasticSearch: A step-by-step guide

Currently, I am utilizing ElasticSearch as a search service within my Spring Web project. The setup involves using the Transport Client to interact with ES. I am curious to know if there is a method available that can generate a QueryBuilder from a JSON D ...

What is the process through which React form elements receive the event parameter?

I'm currently working on a form component that looks like this: import React from 'react'; class CommentBox extends React.Component { constructor(props) { super(props); this.state = { value: '' } this.han ...

What is the reason for the inconsistency in CORS post requests working for one scenario but not the other?

Currently, I am facing an issue while attempting to add email addresses to a mailchimp account and simultaneously performing other tasks using JavaScript once the email is captured. Here's the snippet of my JavaScript code: function addEmail(){ v ...

Loading events for a fullCalendar in node.js using the jade library

I successfully integrated fullCalendar into my nodeJS application using jade and Express, and I have managed to load the calendar. Within the jade file, I pass an array containing events information. How can I display these events on the calendar within th ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

Rendering JSON data in a dropdown menu

When I select an option, all the data is being combined into one row. I want the data to fill each row based on the select option. Any suggestions on what code I should modify or add? Is it related to the loop or should I create a dynamic id for the selec ...

Mastering the art of sorting HTML tables with various columns using JavaScript and jQuery

When they click the button, it should alphabetize the rows in the table according to the clicked column. Is there a way to achieve this sorting functionality without using a javascript/jquery plugin or library? I prefer to develop my own code for this pa ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

Could Express be considered the most reliable and efficient application framework for NodeJS?

While I have some experience with Express, I haven't explored many other Node-based web application frameworks. It's clear that Express is lightweight and versatile, but my usage has been limited to small experimental projects rather than large-s ...

Solutions for resolving the issue of not being able to load images when using merged-images in JavaScript

I have a base64 image here and it has already been converted. data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQSEhUTEhQWFhUXGBoaGBgYGBcXGhgXGBgYGhgbHhoZHiggGholHhgYITEhJSkrLi4uHR8zODMtNygtLisBCgoKDg0OGhAQGi0lICUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0 ...

Vue Selecting Several Options

I am looking to implement multiple selections without using the multiple.vue library. I want to create my own solution. In JavaScript, I have data structured like this: data: roles : [here data] form.roles: [] And here is how I am handling it in m ...