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

Creating a CSS animation to slide a div outside of its container is

I currently have a flexbox set up with two adjacent divs labeled as DIV 1 and DIV 2. By default, both DIV 1 and DIV 2 are visible. DIV 2 has a fixed width, occupying around 40% of the container's width. DIV 1 dynamically adjusts its width to ac ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

Ensure accurate detection of invalid values for SVG Elements in React using jest testing framework

When testing my react app, I am attempting to capture any errors that are thrown or logged to the console. If a regular HTML element such as <p> contains invalid attributes like <p color={false}></p>, react will display an error via cons ...

Navigating the world of cryptocurrency can be daunting, but with the right tools

Hello fellow developers, I've encountered some difficulties with cryptocurrency in my Nativescript project. I am attempting to incorporate the NPM package ripple-lib into my code, but I have been unsuccessful using nativescript-nodeify. How can I suc ...

The two divs are positioned on top of one another, with the link in the bottom div being unclickable

I am trying to create a unique effect where a tile divides into two on hover, with each tile acting as an individual link. Additionally, I want the background color of the tiles to change on hover. To achieve this, I have stacked two divs (toptile and bot ...

Understanding the getJSON MethodExplaining how

$.getJSON( main_url + "tasks/", { "task":8, "last":lastMsgID } I'm a bit confused about how this code functions. I'm looking for a way to retrieve messages from a shoutbox using a URL or some sort of method that the function here ...

javascript mysql and php clash when it comes to loading

I am encountering an issue where I cannot fetch data from my phpMyAdmin database using php code when loading the map api that utilizes javascript. Currently, only the map javascript is being loaded. I have valuable data stored in my database and any assis ...

Attempting to place the search bar within the navigation bar

Having trouble positioning a search bar in my nav bar, I'd like it to show on the right side without overlapping any other elements. Tried relative and absolute positioning with no success so far. Any assistance would be greatly appreciated, thank yo ...

Having trouble with jQuery UI draggable when using jQueryUI version 1.12.1?

Currently, I am diving into the world of jQuery UI. However, I am facing an issue with dragging the boxes that I have created using a combination of HTML and CSS. My setup includes HTML5 and CSS3 alongside jQuery version 1.12.1. Any suggestions or help wou ...

Convert integer data to JSON format using PHPMyadmin

I need to convert a basic database table into JSON format with two fields: id(int), name(varchar) However, when I export it, the output looks like this: [{"id":"1","name":"Mike"}, {"id":"2","name":"Peter"}] The problem is that the id values are enclose ...

In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a ...

Decoding JSON into Java using the Klout API

Currently developing a web application that fetches and displays Klout Scores information for Twitter followers. The process flow is as outlined below: Obtain twitter_id of the followers from Twitter API. For example, retrieve 48,000 ids of Sachin Tendul ...

Event fails to emit when used in conjunction with router-link

I created a basic Vue application: const Home = { template: '<div>Home</div>' } const Bar = { methods: { bar () { alert('bar') this.$emit('test') } }, template: ` <div> ...

Lamenting the Perils of Losing AngularJS Rootscope Data upon Refresh

Currently, I am facing an issue in AngularJS 1.x. When I save a value in the $rootScope and pass to the next page or router, unfortunately, the $rootScope value gets lost upon refreshing the page (F5/Window Reload). I need a solution that doesn't inv ...

How to Use Jquery to Retrieve the Selected Option Value and Append a Parameter

I am attempting to expand the value by adding "&fullpage=true" <select name="navMenu" onchange="go(this.options[this.selectedIndex].value)"> <option value="-">Choose</option> <option value="page.html&amp;nyo=0" class="ccbnLnk" ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...

Generating variables dynamically within a React Native component

In my React Native component, I need to create a variable that will be used multiple times. Each instance of this component should have a different variable name for reference. <View ref={view => { shapeView = view; }} onLayout={({ nativeE ...

The MDL layout spacer is pushing the content to the following line

Here's an interesting approach to Material Design Lite. In this example from the MDL site, notice how the 'mdl-layout-spacer' class positions elements to the right of the containing div, giving a clean layout: Check it out <!-- Event ca ...

An Effective Solution for Resolving the 'Use JsonReader.setLenient(true) to Accept Invalid JSON at Line 1 Column 1 Path $' Issue in Android Studio

I'm facing an issue while attempting to send a POST request to an API. The error message I receive is: To fix the problem, you can use JsonReader.setLenient(true) method in order to accept malformed JSON at line 1 column 1 path $. Is there anyone ...

What is causing Vue to not update a list when using props?

When my App loads, I make an API call in the mounted() method to retrieve a JSON with a list of items. After that, I update the prop set in my target component Homepage: Homepage.pages = resJSON.data.pages; Take a look at the App code below: <template& ...