What is the best way to access nested JSON data in Vue.js code demonstrated here?

How can I properly access the nested JSON data for stage.name provided in the example below?

As shown in the template, my attempt to retrieve the stage name is not working.

Using vue.js

created() {
    url="http://{{ api_endpoint }}"
    fetch(url)
        .then(response => response.json())
        .then(body => {
            for(i=0; i<body.length; i++){
                this.job_execs.push({
                    'name': JSON.stringify(body[i].job.name),
                    'build_id': JSON.stringify(body[i].build_num),
                    'env': JSON.stringify(body[i].job.env),
                })
            }
    })



template: `
      <li v-for="item in this.job_execs">
        [[ item.build_num ]]
        <li v-if="stage in item.job">
          [[ stage.name ]]
        </li>
      </li>
      </ul>

An example API response:

[
    {
        "build_num": 12,
        "job": {
            "name": "test-job",
            "env": "DEV",
            "tool": {
                "env": "DEV",
            },
            "product": {
                "name": "vuejs"
            },
            "platform": {
                "name": "none"
            },
            "stage": [
                {
                    "name": "stage1"
                },
                {
                    "name": "stage2"
                },
                {
                    "name": "stage3"
                },
            ]
        },
]

I think I may need to create a new list in the created hook and start pushing the stage names into it. However, I am concerned about ending up with two separate lists. I'm uncertain about the best approach to take in this scenario.

Answer №1

If you wish to generate an <li> element for each stage, the code would look like this:

<li v-for="stage in item.job.stage">
  [[ stage.name ]]
</li>

Remember to use v-for, not v-if.

Think of v-for as a template equivalent of the following JavaScript snippet:

item.job.stage.forEach(stage => {
    // ...
})

If you only need the first stage, you can simplify it like so:

<li>
  [[ item.job.stage[0].name ]]
</li>

If you want to create a second list based on certain conditions, consider using a computed property instead of the created hook. This will help organize your data and simplify your template.

Update:

The complete structure would be:

<ul>
  <li v-for="item in job_execs">
    [[ item.build_num ]]
    <ul>
      <li v-for="stage in item.job.stage">
        [[ stage.name ]]
      </li>
    </ul>
  </li>
</ul>

Avoid unnecessary JSON.stringify operations in your JavaScript code.

fetch(url)
    .then(response => response.json())
    .then(body => {
        this.job_execs = body
    })

You can also rename keys like build_num to

build_id</code easily using methods like <code>map
:

fetch(url)
    .then(response => response.json())
    .then(body => {
        this.job_execs = body.map(item => {
            return {
                build_id: item.build_num,
                job: item.job
            }
        })
    })

Only perform these transformations if necessary, otherwise keep it simple with this.job_execs = body.

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

Issues with Cordova and JQuery ajax functionality not operating as expected

I am facing an issue with implementing AJAX functionality in my Cordova app (CLI 6.3.1) on Visual Studio 2017. It works fine on the emulator, but I encounter a connection error when installing it on a mobile phone. I have already included CSP as shown bel ...

Issues with HTTPS in Puppeteer and VUE JS

I am encountering an issue when running tests from NODE net::ERR_CONNECTION_REFUSED at https://localhost:8087 at navigate (node_modules/puppeteer/src/common/FrameManager.ts:190:13) Test Suites: 2 failed, 2 total Tests: 7 failed, 7 total Snapshots: ...

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...

Guide on embedding PHP/MYSQL array into an independent JavaScript document

I'm looking for guidance on how to insert an array from a PHP MySQL page into a separate JavaScript file. Can someone please help me with indicating where to include the PHP URL and provide the correct format for the PHP array code in order to achieve ...

Scrolling with animation

While exploring the Snapwiz website, I came across a captivating scroll effect that I would love to implement on my own site. The background picture changes seamlessly as you scroll, with the front image sliding elegantly into view. A similar type of scro ...

Verifying user login on NodeJS through connection from an IIS-hosted website

I am currently upgrading an outdated CMS system and looking to implement a real-time chat feature. The existing CMS operates on IIS, MSSQL, and PHP. The chat feature will be hosted on a separate Linux box running Node.js and Socket.io After successfully ...

Stop images from flipping while CSS animation is in progress

I've been developing a rock paper scissors game where two images shake to mimic the hand motions of the game when a button is clicked. However, I'm facing an issue where one of the images flips horizontally during the animation and then flips bac ...

Using Angular and nativeElement.style: how to alter cursor appearance when clicked and pressed (down state)

I am working with a native elementRef CODE: this.eleRef.nativeElement.style = "_____?????_____" What should go in "???" in order to apply the :active style to the element? (I want to change the cursor style when the mouse is clicked down, not when it is ...

ACE.js enhances website security through Content Security Policy

I've been working on setting up a helmet-csp with ace running smoothly. Here's how my helmet-setup looks: var csp = require("helmet-csp"); app.use(csp({ directives: { defaultSrc: ["'self'", "https://localhost:8000"], ...

Retrieve the component from a JSON dataset

As a newcomer to Python, I am currently working on implementing a small Bellman-Ford algorithm. I have received exchange rates for various currencies in a JSON format as shown below: {"USD_JPY": "88.1911719", "USD_USD": "1.0000000", "JPY_EUR": "0.0086441" ...

The username index is not defined in the file path C:xampphtdocsAppX1signin.php on line 6

Experiencing some challenges with a php script I recently created. As a beginner in php, I understand that my code may not be optimal. These error messages are displayed when the form is submitted: Notice: Undefined index: username in C:\xampp&bsol ...

Unable to be implemented using inline-block styling

I'm struggling to get these 2 elements to display side by side using inline-block, I've tried everything but nothing seems to work. Goal: First element Second element I attempted to modify the HTML code to see if it would yield any results, b ...

Challenges with saving a segment of an AJAX GET response (in JSON) as a string variable

I am facing an issue while attempting to save a section of the result obtained from a GET request through AJAX into a string variable. Essentially, my goal was to ensure that a specific function containing a GET request operation can return the outcome of ...

Import information from a SqlServer Database into a jQuery Full Calendar utilizing the capabilities of Codeigniter3

I've been dealing with this issue for quite some time now. I used to work with the same calendar in PHP, but since my project is in Codeigniter, it's not fitting properly. Therefore, I have switched to working with Codeigniter. Controller Code ...

The functionality of Bootstrap popover is not functioning properly

I'm trying to activate a popover when users hover their mouse over a div. Can I use a popover with a div, or am I missing something in my code? Here's what I have: <div class="grid-item content-text" data-toogle ="popover" data-content="Lorem ...

Encountering syntax errors in GraphQL

Currently, I am in the process of working on the GraphQL Node tutorial and have reached step 7. Visit this link to view Step 7 While implementing the code in my datamodel.prisma file, I encountered several syntax errors: directive @id on FIELD_DEFINITIO ...

Send data in JSON format from an AngularJS client to an Express server

Having an issue when trying to send a JSON Object from an AngularJS $http service to an Express Server. The server receives an empty object: "{}" I've looked at this topic, but it hasn't resolved my problem: angular post json to express This is ...

Attempting to display JSON data retrieved from a decoded base64 string in Python

After attempting to decode a value using base64, my goal is to use the decoded strings individually. Here is an example of my decoded base64 data: { "trailerColor": "FF0017", "complete": 59, "bounds": [ 25, 65, 62, 5 ], "Stamina" ...

Is it practical to use JSON.parse for processing large datasets exceeding 50 megabytes in size?

When developing my android app, I initially used Firebase for real-time data storage. However, due to the high pricing, I made the decision to switch over to a NodeJS server. Since I am new to NodeJS... The Firebase real-time database stores data in JSON ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...