Using Vuejs to iterate over nested data

I am looking to implement a nested v-for loop in Vuejs, but I am unsure about how to structure my Data and the v-for loop itself.

My goal is to iterate through modifiers without having to specify modifiers1, modifiers2 individually.

The idea is to have the first v-for loop iterate through the modifiers object, while a nested v-for loop iterates through the different blocks inside. This way, I can achieve an automatic nested v-for loop.

modifiers1: {
  block1: {
    class: 'doc_button--green',
    description: 'Primary Button'
  },
  block2: {
    class: 'doc_button--orange',
    description: 'Secondary Button'
  },
  block3: {
    class: 'doc_button--red',
    description: 'Tertiary Button'
  }
},
modifiers2: {
  block1: {
    class: 'doc_button--small',
    description: 'Small Button'
  },
  block2: {
    class: 'doc_button--big',
    description: 'Big Button'
  }
}

An example of loop structure that I was considering:

<div v-for="(modifier) in modifiers" :key="modifier">
 <ul v-for="(block) in blocks" :key="block">
   <li></li>
 </ul>
</div>

Is this possible? If so, how should I go about it? Do I need to restructure my Data into a nested array? Thank you

Answer №1

If your data structure is saved in the modifiers variable, you can easily adjust the second v-for loop to iterate over the modifier variable from the initial v-for.

Here's an example snippet showing how you can utilize data from the loops:

let modifiers = {
  modifier1: {
    block1: {
      class: 'doc_button--green',
      description: 'Primary Button'
    },
    block2: {
      class: 'doc_button--orange',
      description: 'Secondary Button'
    },
    block3: {
      class: 'doc_button--red',
      description: 'Tertiary Button'
    }
  },
  modifier2: {
    block1: {
      class: 'doc_button--small',
      description: 'Small Button'
    },
    block2: {
      class: 'doc_button--big',
      description: 'Big Button'
    }
  }
}
<div v-for="(blocks, modifier) in modifiers" :key="modifier">
  <ul v-for="(block, name) in blocks" :key="name">
    <li v-for="(value, key) in block" :key="key">{{key}}: {{value}}</li>
  </ul>
</div>

Answer №2

To access the data in Vue, you can create a computed property that references the $data object...

computed:{
    myData() {
        return this.$data
    }
},

Then include it in your template like so...

<div v-for="(item) in myData" :key="item">
    <ul v-for="(subItem,key) in item" :key="key">
        <li>{{ subItem.description }}</li>
    </ul>
</div>

Check out the live demo here!

Answer №3

Another approach is to convert the Object into an array of modifiers, each containing a sub-array of blocks:

const elements = {
  modifier1: {
    section1: {
      type: 'paragraph',
      content: 'Introduction'
    },
    section2: {
      type: 'image',
      content: 'Main Picture'
    },
    section3: {
      type: 'video',
      content: 'Product Demo'
    }
  },
  modifier2: {
    section1: {
      type: 'heading',
      content: 'Title Header'
    },
    section2: {
      type: 'link',
      content: 'Learn More'
    }
  }
}
const sections = Object.keys(elements).map(modifier => ({
  name: modifier,
  subsections: Object.keys(elements[modifier]).map(section => ({
    ...elements[modifier][section],
    name: section
  }))
}));


console.log(sections);

You can then iterate through the nested arrays like this:

<div v-for="(section) in sections" :key="section.name">
 <ul v-for="(subsection) in section.subsections" :key="subsection.name">
   <li></li>
 </ul>
</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

An error in typescript involving a "const" assertion and a string array

Currently, I am diving into the world of Typescript along with React. However, an error has emerged in my path that I can't seem to figure out. It's puzzling why this issue is occurring in the first place. Allow me to elaborate below. const color ...

Loop through a series of objects using a for loop

I need help with looping through a set of objects using a for loop, but I'm encountering an issue because they do not have the same name. <div id="components-demo"> <div>Travel Information</div> <ul> <li ...

Issue with Vue multiselect preventing creation of new tags

Having a functional Vue multiselect feature that utilizes an autocomplete function via an axios call to a database. The process of retrieving DB results, adding them as options, and turning them into tags works seamlessly. The main issue arises when tryin ...

How can I access 'this' in a Nuxt plugin?

Have you ever wondered how to create a plugin in nuxt like this? const utilities = { name: utils, emmitModel(name, val) { const value = Object.assign({}, this.value) value[name] = val this.$emit('input', value) }, } export defa ...

Struggling to get troika-three-text installed via npm?

I'm having trouble integrating Troika with my three-js scene. While others seem to have no issue, I am struggling to call the module and encountering problems with references. It's frustrating because I can't seem to find any resources to he ...

Mastering the art of Promises and handling errors

I've been tasked with developing a WebApp using Angular, but I'm facing a challenge as the project involves Typescript and asynchronous programming, which are new to me. The prototype already exists, and it includes a handshake process that consi ...

Learn the process of applying distinct CSS classes to various elements within an AJAX response

The client initiates an AJAX call via jQuery. Upon fetching data from the database, I return the response which includes the application of numerous classes and styles to various HTML tags. Unfortunately, this process results in code that appears unsightly ...

What is the proper way to retrieve an object from a json file?

My JSON structure looks like this: { "total": 4367, "page": 1, "per_page": 10, "paging": { "next": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=2", "previous": null, "first": "/v ...

reach an agreement on the implementation of infinite scrolling when navigating backwards

I'm looking to create a feature where clicking the back button will return me to the same position on the page. A great example of this is on . If you scroll down, click on a product, and then go back from the product page, you'll be taken back t ...

How to display an unordered list horizontally in HTML

I'm working on a screen that has filters displayed vertically, but I want to align them horizontally and have the filter options arranged in two columns. I've tried using CSS properties like spacing, clear, and display block, but the checkboxes/l ...

The Numpy.count_nonzero function experiences a malfunction on the 64-bit Windows operating system

While my code runs smoothly on my Linux system, it crashes Python when a colleague tries to run it on their Windows system. After some investigation, I discovered the issue lies with the Numpy function non_zero. Can anyone shed light on why this is happeni ...

Cloned bootstrap nav tabs are controlled just like the original version

I have a unique scenario where I need to generate a series of "cards" with tabs on top (each card having tabs). To accomplish this, my plan was to use a template element that I can clone and then populate. Everything seems to work fine, except for the tabs ...

Looking for a way to deactivate the loader after the submission is complete

Seeking to implement a loader on my asp.net webforms app. Here's my javascript loader: function loading() { $("#loading").show(); } function loaded() { $("#loading").hide(); } html loader ...

Looking to eliminate the unchecked checkbox value from the list using jQuery?

After selecting a checkbox, the text/value is displayed in an li element. However, if I uncheck the first box and check the second one, I want to remove the text/value associated with the first checkbox as shown below: View Image Here Here is my code sni ...

Invoke a distinct class function using either JavaScript or jQuery

During a recent interview, I was asked about calling a method that exists in a different class. For example, consider the following: public class EmployeeDept { public void showNames() { //display list of names } } The interviewer wanted to kn ...

When I start a new Vue3 project, I notice that there are two elements within the <template> section and my VScode gives me a

https://i.sstatic.net/fJK0b.png Hey guys, I am currently transitioning from Vue2 to Vue3. In Vue2, you are restricted from placing more than one element within the <template></template> tags. However, in my new Vue3 project, I noticed that th ...

Loading web pages using ajax and handling relative paths

My method involves using ajax to load HTML files when links on my page are clicked. The process is simplified as follows: links.click(function () { var href = $(this).attr("href"); history.pushState(null, null, href); $.get($(this).attr("href" ...

Tips for ensuring that the "this" in React ES6 static method is bound to the lexical scope

Currently in React with ES6 via babel, my goal is to develop a static method that can update the state of the Component it belongs to by accepting an object as an argument. However, I'm facing an issue where "this" is not bound to the lexical scope. ...

Executing directives in a sequential manner

I am facing a challenge with my HTML view that is filled with multiple Angular directives, each triggering numerous HTTP requests. This has resulted in high CPU usage due to the heavy load. Our proposed solution is to load one directive at a time, allowing ...

Vue | Passing data to parent using eventbus

Is there a way in Vue to broadcast all emitters to the parent listening component? For example, can we simplify this code: <DetailsPages v-if="$route.hash === '#details_pages'" v-on:next="$emit('next')" v-o ...