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

Integrating Firebase into Vue.js 2 application using Vue CLI with webpack configuration

Recently, I started using vue-cli with a webpack template and I'm looking to integrate Firebase as my database for the Vue app. Here's how I imported Firebase into my app: Main.js //imported rest all required packages just dint mention here imp ...

Switch out the content within a div upon selection

I'm currently working on a palette board project and facing some challenges when switching to a different theme. The initial page is set to have a Warm color palette, but I intend to alter this once the user clicks on the All theme option. Users wil ...

The Three.js environment experiences lag and a decrease in performance

In the threejs scene, there is a sphere geometry and a plane geometry. The sphere is textured with an image, while the plane geometry is textured with 2D text. The plane geometry is also attached with a click event. When clicking on the plane geometry, ...

Steps for deactivating a button based on the list's size

I am trying to implement a feature where the user can select only one tag. Once the user has added a tag to the list, I want the button to be disabled. My approach was to disable the button if the length of the list is greater than 0, but it doesn't s ...

Incorporate a corner box feature to bring attention to the typed.js functionality

I have successfully integrated typed.js into my project and now I am looking to replicate the highlighted text with an excel-like box in one corner. I've managed to get the text typing out while also adding an SVG for the box in HTML, but I'm hav ...

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

Tips for displaying the date in 13-digit Unix Timestamp format using JSpreadSheet

I am faced with a challenge involving data that is stored in Unix Timestamp format, which I need to display as a readable date (e.g. YYYY/MM/DD) in JSpreadSheet ("jspreadsheet-ce"). Currently, the data appears as a 13-digit number and looks unattractive. ...

When choosing an input field, it consistently yields an undefined value

Whenever I attempt to select an option in the input field, it should set the state value to the selected option. However, it keeps returning undefined. I am utilizing Semantic UI React Forms for input, but every time I select an option and submit, it retu ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

Personalize the "set up notification" PWA on React

Is it possible to customize this default design, including the picture, title, description, and background? I made changes in manifest.json, but nothing seems to have happened. Here is a picture of the random install prompt that I would like to customize ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

Transforming DOM elements into Objects

Here are some values that I have: <input name="Document[0][category]" value="12" type="text"> <input name="Document[0][filename]" value="abca.png" type="text" > I am looking for a way to convert them into an object using JavaScript or jQuer ...

I encountered a frustrating issue with saving user input data using localStorage

One of my goals is to store the current inputs even if the user refreshes or closes the browser. The issue I'm facing is that when I select Yes in the radio button, then refresh the page or close the browser and reopen it, the No button is checked wh ...

What is the best way to add a key to a JavaScript array while keeping it reactive in Vue.js?

If there's an array in the state: state: { users: [] }, Containing objects like: { id: 1, name: "some cool name" } To add them to the store using a mutator like users.push(user);, how can we ensure that instead of 0:{...}, it uses the ...

What is the importance of maintaining immutability for objects in Redux?

What is the importance of immutability in Redux? While I understand that frameworks like Angular2 use onPush to leverage immutability for quicker rendering of views, I'm interested in learning about other reasons why Redux emphasizes immutability desp ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

What steps should I take with my Android PWA manifest and service workers?

I created a web application that I want to prompt Android users to download when they visit. To build my service workers and manifest, I utilized PWA Builder which can be found at Now that I have the manifest file ready, should I simply upload it to the r ...

Click event not functioning correctly in Internet Explorer

When using jQuery, I have the following code: <script type="text/javascript"> $(document).ready(function(){ $('body').on('click', '.add-photo',function() { $("#images").append($('<input/>').attr(&apo ...

Is it possible to preserve the <canvas> elements to use for future animation frames?

Currently, I am working on a graph visualization project that involves complex calculations being done on an HTML5 canvas. My goal is to create an interactive animation where the graph remains fixed, but additional elements are overlaid as the mouse moves ...

Struggling to achieve desired output from function in NextJS

I'm a bit confused by the code below. The itmLoop function seems to work fine when placed directly in the return section, but nothing is output when it's called as shown below? I'll eventually need to make it recursive, so I have to keep i ...