Looping through data and converting it into a JSON format can

Can anyone help me figure out how to work through this JSON data using VUE? I'm having trouble accessing keys that v-for can't seem to reach:

[
    {
        "Lavandería": {
            "id": 1,
            "name": "Lavandería",
            "img": "rinse.png",
            "Servicios": [
                {"model":"Sentra", "doors":4},
                {"model":"Maxima", "doors":4},
                {"model":"Skyline", "doors":2}
            ]
        },
        "Tintorería": {
            "id": 2,
            "name": "Tintorería",
            "img": "shirt-2.png",
            "Servicios": [
                {"model":"Sentra", "doors":4},
                {"model":"Maxima", "doors":4},
                {"model":"Skyline", "doors":2}
            ]
        },
        "Planchado": {
            "id": 3,
            "name": "Planchado",
            "img": "iron.png",
            "Servicios": [
                {"model":"Sentra", "doors":4},
                {"model":"Maxima", "doors":4},
                {"model":"Skyline", "doors":2}
            ]
        },
          "Otros": {
            "id": 4,
            "name": "Otros",
            "img": "wring.png",
            "Servicios": [
                {"model":"Sentra", "doors":4},
                {"model":"Maxima", "doors":4},
                {"model":"Skyline", "doors":2}
            ]
        }
    }
]

I need to extract the id and image of each item first, in order to access their respective "Services" data.

My attempt with v-for looks like this:

v-for="item in services" :key="item.id"

However, I am unable to even retrieve the IDs. When I console.log it as follows, I see the data but still struggle with implementing it in VUE: console.log(this.services[0].Lavandería.id);

Answer №1

Another way to iterate is by looping through an object:

<ul v-for="(service, index) in services" :key="index">
  <li v-for="(item, key) in service" :key="key">{{key}}: {{item}}</li>
</ul>

Check out the JsFiddle example here

If there's only one object in the array, you can access it directly using services[0] instead of using a v-for loop.

Answer №2

It is essential to have a clear understanding of your JSON structure.

[
  {// initial loop iteration
     'a': { // first nested loop
       id
     },
     'b': { // second nested loop
       id
     }
  },
  {// initial loop iteration
     'a': { // first nested loop
       id
     },
     'b': { // second nested loop
       id
     }
  }
]

new Vue({
  el: '#app',
  data: {
    services: [
      {
          "Lavandería": {
              "id": 1,
              "name": "Lavandería",
              "img": "rinse.png",
              "Servicios": [
                  {"model":"Sentra", "doors":4},
                  {"model":"Maxima", "doors":4},
                  {"model":"Skyline", "doors":2}
              ]
          },
          "Tintorería": {
              "id": 2,
              "name": "Tintorería",
              "img": "shirt-2.png",
              "Servicios": [
                  {"model":"Sentra", "doors":4},
                  {"model":"Maxima", "doors":4},
                  {"model":"Skyline", "doors":2}
              ]
          },
          "Planchado": {
              "id": 3,
              "name": "Planchado",
              "img": "iron.png",
              "Servicios": [
                  {"model":"Sentra", "doors":4},
                  {"model":"Maxima", "doors":4},
                  {"model":"Skyline", "doors":2}
              ]
          },
            "Otros": {
              "id": 4,
              "name": "Otros",
              "img": "wring.png",
              "Servicios": [
                  {"model":"Sentra", "doors":4},
                  {"model":"Maxima", "doors":4},
                  {"model":"Skyline", "doors":2}
              ]
          }
      }
  ]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<html>
<body>
  <div id="app">
    <div v-for="(service, key) in services" :key="key">
      <div v-for="item in service" :key="item.id">
        id: {{ item.id }}<br>
        name: {{ item.name }}
      </div>
    </div>
  </div>
</body>
</html>

Answer №3

If you're looking to streamline access to all services within each object and display them in a linear fashion, consider transforming the service array into a flat array.

For example, if your data is an array with objects containing multiple top-level keys:

In your template

v-for="item in getServices(arr)"

In your vue model

new Vue({
    //....
    methods: {
        //...
        getServices(arr){
           let obj = arr[0];
           return [].map.call(Object.keys(arr[0]), k => {
                   return obj[k].Services
               }).reduce((acc, val) => acc.concat(val));
        }

    }
})

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

The functionality of jQuery's appendTo method seems to be malfunctioning

I am trying to display an image with a popup using jQuery mobile. In my loop, I have the code below: for( var i = 0; i < imageArray.length; i++ ) { counter ++; // Create a new Image element var img = $('<img data-rel="popup" class=" ...

Having trouble using the elementIsNotVisible method in Selenium WebDriver with JavaScript

I'm struggling to detect the absence of an element using the elementIsNotVisible condition in the Selenium JavaScript Webdriver. This condition requires a webdriver.WebElement object, which is problematic because the element may have already disappear ...

Make the object rotate around a specified vector point

I have been trying to figure out how to make an object orbit around the vector coordinates 0,0,0. Specifically, if the object is at X300, Y50, Z200, I want it to revolve around 0,0,0 without changing the position on the Y axis. Math isn't my strong su ...

Issue: Vue.js v-model does not function correctly when used in conjunction with a v-for loop

Recently, I began exploring Vue.js and I have encountered what seems like a straightforward issue... Let me explain my current situation: var app = new Vue({ el: "#app", data: { utilizador:{ nome:"Luis Abreu", ...

Generating variable names dynamically in JavaScript

To prevent a javascript heap issue, I implement the usage of multiple arrays including 'family1', 'family2','family3' and 'dogs1', 'dogs2', 'dogs3'. For instance, you can use 'family1 and dog ...

Confused between Javascript and PHP? Here's what you should consider!

Looking for a solution to transfer a string from JavaScript, obtained from the content of a div, to PHP in order to create a text file with this information. What would be the most effective approach to accomplish this task? Edit[1]: Using the Post ...

Does Firestore arrayunion offer any kind of callback function?

Hey there! I'm currently working on a voting system and I want to prevent the same user from voting multiple times on the same post. let db = firebase.firestore(); var postRef = db.collection("posts").doc(this.pid); postRef.update({ ...

ms-card malfunctioning due to data issues

I'm facing difficulties in transferring the data to the template. Although I can access the data in HTML using vm.maquinas and maquina, I am unable to pass it to the TEMPLATE through ng-model. Information about ms-cards was not abundant. Module ang ...

I would like to exclude the item within my ng-repeat loop using ng-if

I'm attempting to utilize ng-if within ng-repeat in order to create Accordions. Depending on the condition value, I want certain items to be skipped in the ng-repeat. For example, if item.condition is true, then only display the accordion. The code b ...

cycle through several handlebars entities

Hey friends, I could really use your help right now. I'm attempting to iterate through these objects using handlebars. RowDataPacket { idUser: 1, username: 'xxxxxx', password: 'xxxxx', fullname: 'Julian Rincon'}, RowDat ...

Guide to implementing a delay in JavaScript/jQuery code right after invoking an asynchronous function

Is there a way to execute an asynchronous function and then introduce a delay in the subsequent code execution to ensure that the asynchronous operation has completed? I want to avoid wrapping the following code in a function and delaying it, I simply ne ...

The most effective method for acquiring an object through inheritance

I'm seeking advice on the best practice for adding behavior to an object received as a JSON object. I have REST services that allow me to define a sort of state machine. The API defines a /sessions resources. When creating a session via POST /sessio ...

axios displays a CORS error when interacting with a Django REST framework

Greetings to all who are tuned in. Currently, I am engrossed in the world of vuejs SPA coupled with flask and django backends. Yes, you read that right - two separate backends! The application is undergoing a significant transition at the moment. I am in t ...

"Seeking assistance with concept sharing and content transmission. In need of guidance

Basic Question I'm stuck trying to brainstorm a concept to reach my objective. I am having trouble figuring out how to navigate the DOM correctly with my chosen method. The Objective First, let me explain what I am doing: I use ajax to bring HTML ...

Enhance the functionality of your React app by making the `<Paper>` component in Material UI clickable

I'm trying to figure out how to make a Paper component clickable. I attempted to set an id property in the tag like () and then utilize the DOM to add an event listener, but it's not working. I've hit a roadblock and I'm running out of ...

A guide to importing a Vue component in a JavaScript file

I am looking to achieve a specific behavior in my project: depending on a condition stored in my database, I want to load a particular vue.component instead of another. For example, within a file named discover.js, there is the following code: Vue.compone ...

What is the method for sending parameters to PHP from an HTML file using AJAX?

My protfolio.html file contains a table #gallery with different categories. I want to dynamically update the content of the #gallery based on the selected category using ajax. I have a php file that scans a specific folder for images related to the categor ...

Change a PNG file into a three.js plane by converting it into height

I have a visualization challenge using three.js. I am working with an image linked here: https://i.sstatic.net/EzfcS.png. I am using a plane geometry and I aim to adjust the height of the plane according to this other image: https://i.sstatic.net/hMj91.png ...

Leveraging Next.js to efficiently handle multiple asynchronous requests with NextResponse

I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 4 ...

Astro/Vue runs the appEntrypoint once for each component

I have included several Vue components within an Astro page that are sharing state using Pinia To set up the Pinia plugin, I followed the instructions in the Astro documentation and added the initialization code to my astro.config.mjs: import {defineConfi ...