Converting a JSON object into a Vue v-for friendly structure

My goal is to display data in an html table using the Vue.js v-for directive. However, I'm encountering issues with building the table. I suspect that the data format is incorrect, and I may need to manipulate it to eliminate the object layer (index of each item).

I attempted to use the .map function without success.

Vue.js

callStocks = function () {
          var app = new Vue({
            delimiters: ["[[", "]]"],
            el: "#stocksTable",
            data: {
              stocks: []
            },
            created() {
              axios
                .get("getStocksAvailable/")
                .then(response => {
                    var data = response.data.data
                    this.stocks = data.map(item => item.fields)
                    console.log (data)
                });
            }
          });
};

callStocks();
<table>
 <thead>
  <tr>
   <th>Company</th>
  </tr>
 </thead>
 <tbody id="stocksTable">
  <tr>
   <td v-for="item in stocks">[[ item.stockName ]]</td>
  </tr>
 </tbody>
</table>

Console.log:

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

Vue.js devtool object:

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

Answer №1

The map function does not alter the original array; instead, it generates a new one.

Therefore, you can use either

this.stocks = data.map(item => item.fields)
or [[ item.fields.stockName ]]

Additionally, it is important to note that the data parameter must be a function.

Answer №2

If you have already defined the stocks attribute, there is no need to worry about reactivity. However, I suggest making some changes to your template and paying attention to how you structure your data as well.

callStocks = function () {
    var app = new Vue({
        delimiters: ["[[", "]]"],
        el: "#stocksTable",
        data: () => ({
          stocks: []
        }),
        created() {
            axios
            .get("getStocksAvailable/")
            .then(response => {
               var data = response.data.data
                this.stocks = data.map(item => item.fields)
                console.log(data)
            });
        }
    });
};

callStocks();

It seems like your template is currently iterating inside a single row. If you intend to display one stock name per row, you need to make some adjustments.

...
<tbody id="stocksTable">
  <tr v-for="item in stocks">
    <td>[[ item.stockName ]]</td>
  </tr>
</tbody>
...

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

Tips for incorporating a hyperlink into a Vuikit table using Vue.js

I've exhausted all my options trying to make this work, and I'm on the verge of removing Vuikit... All I want is to pass dynamic data to the component, create a new HREF with that data, and have a clickable LINK text element displayed :) Here&a ...

Encountering a CSS problem while attempting to design a section featuring a background image

On this page, I have the login bar on the right and the footer at the bottom. I want a div to sit in the area currently occupied by the background image and fill it with the full background image. Currently, everything is wrapped in a wrapper and the back ...

Execute a post request upon clicking with NEXT JS, while also firing off a get request

I'm facing an issue where I need to post and get my data when clicking on the same button (similar to writing and displaying comments). However, whenever I click the button, everything seems to be working fine but a request with a 304 status code star ...

What steps should be taken to resolve the update problem in Sequelize?

Having an issue with the update method in MySQL ORM. User.update({ ResetPasswordToken : resetPasswordToken },{ where: { UserName: 'testuser' } }) Receive this Sequelize Log: Running query: UPDATE Users SET ResetPasswordToken=?,updat ...

JSP checkbox functionality

I have been attempting to solve this issue since last night, but I am struggling and need some help. There are two pages, named name.jsp and roll.jsp. In name.jsp, there are two input text boxes and one checkbox. After entering data in the text boxes and ...

Utilizing a functional component to incorporate a "load more" button in ReactJS

Hey everyone, I've come across this ReactJS code that I need some help with: function DisplaySolutions({solutions}) { const topSolutions = solutions.slice(0, 4); const remainingSolutions = solutions.slice(4); const [isD ...

Removing an element from an object using ng-model when its value is empty is a standard practice

Utilizing the $resource service to access and modify resources on my API has been a challenge. An issue arises when the ng-model-bound object's value is set to empty - the bound element is removed from the object. This results in the missing element ...

Complete interaction with child processes in Node.js

I have a basic C++ program compiled using the command gcc 1.cpp -o 1.exe. // 1.cpp #include <stdio.h> int main(){ int num = 0; scanf("%d", &num); printf("%d", num + 1000); scanf("%d", &num); printf("\n%d", num + 1000); ...

Unable to retrieve data from PHP using AJAX request

My project consists of 3 interconnected files: index.php, functions.js, and compute.php In index.php, there is a div that triggers a function in functions.js called compute(), which sends an AJAX request to perform a task in compute.php The code in index ...

Leveraging variables from views.py in JavaScript

My approach to populating a user page has evolved. Initially, users would choose a value from a drop-down and an AJAX call would retrieve data. Here is the code that was functioning: HTML: <h3>Experimenter: {{ request.user }}</h3> <h3>R ...

How can I isolate the CSS of my Vue application from the rest of the website?

I am currently working on developing a unique "plugin" that will feature a user interface to be integrated into various vendor websites. This particular plugin is designed to be CMS agnostic, and due to SEO concerns, I am unable to utilize an iframe. My go ...

Modifying JQuery function to target two IDs instead of just one

I am utilizing a bootstrap 5 tablist on my website that allows for navigating between tabs using custom left and right arrows. If I wish to introduce a second bootstrap 5 tablist with a new unique ID, how can I modify the code to integrate the new ID and e ...

Getting a result from a Node.js function that includes a database query

Currently, I am diving into the world of Node.js and delving into working with MySQL connections. There is a particular function that should retrieve a set of rows from the database successfully. However, after retrieving these rows, I am unsure of how to ...

Seeking guidance on capturing the correct error message when using JSON stringify?

Imagine I have an object structured as follows var obj = { "name": "arun" age } After attempting JSON.stringify(obj), it results in an error due to the improper structure of the obj. I am interested in capturing this error displayed in the console and pr ...

Mocha maintains the integrity of files during testing

After running a unit test to update a config file, I noticed that the file was altered. My initial thought was to use "before" to cache the file and then restore it with "after". mod = require('../modtotest'); describe('Device Configuratio ...

What is the best way to retrieve the value from a textbox on the client side and then utilize it to generate

I am currently utilizing jQuery for my modal dialogs. My goal is to open a model dialog from one page and send some additional query strings to the modal dialog page. Is there a way to achieve something like this? <asp:HyperLink ID="hypClientSearch" ru ...

PHP - implement a button that triggers an AJAX request to switch languages

I am trying to find a basic PHP script that can modify a variable when a button is clicked to display different languages. Can anyone help me with this? Click on the button to change language options: English - value= en French - value= fr When I click ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants & ...

tips for transitioning between various json entities

Recently, I created a login page code using JavaScript that runs on a Node Express.js server. Users can input their username/email and password, and all the data gets stored in a JSON file structured like this: {"username":"admin"," ...

Utilizing Sinon.js for inline callbacks upon successful execution

Currently, I am utilizing QUnit, Sinon.js (specifically fakeServer), and jQuery (for AJAX) to capture and test AJAX calls within my program. One issue that I am encountering pertains to the inconsistency where inline-function calls are not being executed. ...