Show nested arrays in Vue.js exhibition

As a newcomer to vue, I've been navigating my way around with some success.

Lately, I've been dealing with JSON data structured like this:

[
  {
    "name": "jack",
    "age": "twenty",
    "Colors": {
      "favorite": "blue",
      "hate": "orange",
      "surprise": "violet"
    },
   
    "Food": {
     "favorite": "barbecue",
      "hate": "broccoli",
      "surprise": "pasta",
      "new": [
        "pizza",
        "ice cream"
      ]
    }
  }
]

My goal is to present the data in a more readable format like so:

Name: Jack

Age: Twenty

Colors

  • Favorite: Blue
  • Hate: Orange
  • Surprise: Violet

Food

  • Favorite: Barbecue
  • Hate: Broccoli
  • Surprise: Pasta
  • New:
    • Pizza
    • Ice cream

Here's the HTML code I used:

<p><strong>Name:</strong> Jack</p>
<p><strong>Age:</strong> Twenty</p>
<p><strong>Colors</strong>
   <ul>
      <li><strong>Favorite:<strong> Blue</li>
      <li><strong>Hate:<strong> Orange</li>
      <li><strong>Surprise:<strong> Violet</li>
   </ul>
</p>
<p><strong>Food</strong>
   <ul>
      <li><strong>Favorite:<<strong> Barbecue</li>
      <li><strong>Hate:<<strong> Broccoli</li>
      <li><strong>Surprise:<strong> Pasta</li>
      <li><strong>New:<strong>
         <ul>
            <li>Pizza</li>
            <li>Ice cream</li>
        </ul>
     </li>
   </ul>
</p>

Initially, I attempted to use the following code:

HTML

  <div v-for="(item, index) in items" :key="index">
       <div>
          <p><strong>{{title}}</strong> {{item}}</p>
          <p v-for="(category, index) in item" :key="index"><strong>{{index}}</strong> {{category}}</p>
       </div>
    </div>

Script

import axios from 'axios'
    export default {
        name: 'theComponent',
        props: {},
        data() {
            return {
                items: []
            }
        },
        mounted() {
            const url = 'https://api-json-url'
            axios.get(url)
                .then(response => {
                    this.items= response.data[0]
                })
        }
    };

However, I encountered some issues:

Name: Jack

0:J

1:a

2:c

3:k

Age: Twenty

0:T

1:w

2:e

3:n

1:t

2:y

Colors: {"favorite": "blue","hate": "orange","surprise": "violet"}

  • Favorite: Blue
  • Hate: Orange
  • Surprise: Violet

Food {"favorite": "barbecue","hate": "broccoli","surprise": "pasta","new":["pizza","ice cream"]}

  • Favorite: Barbecue
  • Hate: Broccoli
  • Surprise: Pasta
  • New:["pizza","ice cream"]

HTML


    <p><strong>Name:</strong> Jack</p>
    <p><strong>0</strong>J</p>
    <p><strong>1</strong>a</p>
    <p><strong>2</strong>c</p>
    <p><strong>3</strong>k</p>
    <p><strong>Age:</strong> Twenty</p>
    <p><strong>0</strong>T</p>
    <p><strong>1</strong>w</p>
    <p><strong>2</strong>e</p>
    <p><strong>3</strong>n</p>
    <p><strong>1</strong>t</p>
    <p><strong>2</strong>y</p>
    <p><strong>Colors</strong> {"favorite": "blue","hate": "orange","surprise": "violet"}</p>
    <p>
       <ul>
          <li><strong>Favorite:<strong> Blue</li>
          <li><strong>Hate:<strong> Orange</li>
          <li><strong>Surprise:<strong> Violet</li>
       </ul>
    </p>
    <p><strong>Food</strong> {"favorite": "barbecue","hate": "broccoli","surprise": "pasta","new":["pizza","ice cream"]}</p>
    <p>
       <ul>
          <li><strong>Favorite:<strong> Barbecue</li>
          <li><strong>Hate:<strong> Broccoli</li>
          <li><strong>Surprise:<<strong> Pasta</li>
          <li><strong>New:<strong>["pizza","ice cream"]</li>
       </ul>
    </p>

I've considered using isArray() and implementing some v-if logic before looping through the data. Unfortunately, my attempts haven't been successful. I even tried checking for array length without any luck.

Answer №1

I took a shot at creating a preliminary version inspired by your example on CodePen: Check it out here

Basically, the approach involves iterating through the items and verifying if the value is an array or object. If so, you would need to iterate through them again in a nested manner like this:

<div id="app">
  <div v-for="(item, index) in Object.entries(items[0])" :key="index">
    <div v-if="typeof item[1] != 'object'">
      <p>
        <strong>{{item[0]}}:</strong> {{item[1]}}
      </p>
    </div>
    <div v-else>
      <p>
        <strong>{{item[0]}}:</strong>
        <ul>
          <li v-for="(innerItem, innerIndex) in Object.entries(item[1]) ">
            <div v-if="!Array.isArray(innerItem[1])">
              <p>


                <strong>{{innerItem[0]}}:</strong>
                <span>{{innerItem[1]}}</span>
              </p>


            </div>
            <div v-else>
              <strong>{{innerItem[0]}}:</strong>

              <ul>
                <li v-for="(it2,in2) in innerItem[1]">{{it2}}</li>
              </ul>
            </div>
          </li>
        </ul>
      </p>
    </div>
  </div>


</div>

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

Are there any debugging tools specific to Internet Explorer for JavaScript?

I need a reliable JavaScript debugger for Internet Explorer. I have tried using Firebug Lite, but it doesn't seem as detailed as the original Firebug when it comes to displaying JavaScript errors. Does anyone know how to pinpoint JavaScript errors in ...

What could be causing my Ajax function to malfunction?

I've been attempting to incorporate a form that sends two javascript variables to a php script and displays the result in a new Div on the same page using an ajax function. Unfortunately, it's not functioning as expected. Here is the code snippe ...

Click on the link to open it in a SharePoint modal and populate it with the value from the

After populating a ng-grid with SharePoint items, my goal is to have the SharePoint edit form open in a modal window when the edit button at the end of each row is clicked. However, I am encountering difficulties when using OpenPopUpPage as the {{row.entit ...

Is my data secure in Node.js RAM?

I have developed a web application that enables users to create personal pages using Express and Node.JS. Each page is represented as an object, allowing for the creation of new ones with the syntax: new privatePage(name, pswd). As a result, all passwords ...

Is there a more "Angular-esque" approach to implementing this (inter-element communication)?

I have created a custom directive that will automatically add an asterisk to the label of any input field marked as required. The following is my link function with detailed comments: // This is what the DOM structure looks like: // <label id="label-1" ...

change visibility:hidden to visible in a css class using JavaScript

I've put together a list of Game of Thrones characters who might meet their demise (no spoilers included). However, I'm struggling with removing a CSS class as part of my task. Simply deleting the CSS is not the solution I am looking for. I' ...

Display radio buttons depending on the selections made in the dropdown menu

I currently have a select box that displays another select box when the options change. Everything is working fine, but I would like to replace the second select box with radio buttons instead. Can anyone assist me with this? .sub{display:none;} <sc ...

The Node.js JSON string displays as "[object Object]" in the output

Front End // js / jquery var content = { info : 'this is info', extra : 'more info' } $.ajax({ type: 'POST', url: '/tosave', data: content }); Node // app.js app.post('/tosave', funct ...

Unable to retrieve the complete count of invitations made by a user

My goal is to retrieve the invites of the author of a specific command within one server. I have experimented with various solutions, but many appear outdated or incorrect. Here is my current approach: exports.run = async (client, message, args) => { ...

Is it possible to use ref in React to reference various elements based on specific actions?

I'm having trouble targeting the clicked button using a ref as I always get the second one. Any ideas on how to solve this issue? Also, if I have a native select element with two optgroups, is it possible to determine from which optgroup the selection ...

Troubleshooting the issue of AJAX not successfully transmitting variables to PHP

let xmlhttpRequest; if (window.XMLHttpRequest) { xmlhttpRequest = new XMLHttpRequest(); } else { xmlhttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttpRequest.open("POST", "test.php", true); xmlhttpRequest.setRequestHeader("Content-typ ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

Loading local JSON data using Select2 with multiple keys can greatly enhance the functionality

Comparing the select2 examples, it is evident that the "loading remote data" example contains more information in the response json compared to the "loading array data" example. I am interested in knowing if it is feasible to load a local json file with a ...

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

What is the difference between using 'classes' and 'className' in Material UI?

I find myself a bit perplexed about these two properties. Let's say I have, const useStyles = makeStyles(() => ({ style: { width: 600, height: 400, }, })); With this, I can use, const classes = useStyles(); <SomeComponent classNa ...

Establishing a user session with Node.js

I am new to the world of node.js and JavaScript in general. I have a piece of code that currently handles login functionality by checking if a user exists in a MYSQL database. This part is functioning correctly. Now, I wish to improve this feature by crea ...

What is the process for executing JavaScript code that is stored as a string?

After making an AJAX call, I receive a random string (constructed dynamically on the server) that contains JavaScript code like: Plugins.add('test', function() { return { html: '<div>test</div&g ...

Node.js powered file uploading on the Heroku platform

After attempting to upload a file to Heroku using https://www.npmjs.com/package/express-fileupload, I encountered an error. It worked fine on my PC, but on Heroku, I received the following error message: {"errno":-2,"code":"ENOENT","syscall":"open","path" ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...