Guide on embedding an array within another object array using Vue Js

In my work with Laravel Vuejs, I retrieve an object array named arrayService from the database. Using axios, I make a GET request to obtain this array and display it.

var app = new Vue({
  el: '#app',
  mounted() {
  //this.getService()
  },
  data() {
    return {
    arrayService: [
        { service: '2', format: [".mp3",".mp4"] },
        { service: '3', format: [".jpg",".png"] },
      ],
    arrayFormat: [".mp3",".mp4",".jpg",".png"]
    }
  },
  methods:
  {
    getService() { 
      axios.get('/').then(function(response){
        this.arrayService = response.data

        /*I GET FROM THE DATABASE 
       arrayService: [
        { service: '2', format: [".mp3",".mp4"] },
        { service: '3', format: [".jpg",".png"] },
      ],
       */
          $.each(response.data, function (key,value) {
            $.each(JSON.parse( value.format ), (key,element) => { 
               this.arrayFormat.push(element)
               
        /*RESULT OF PARSE:
       arrayFormat: [
          { [".mp3",".mp4",".jpg",".png"] }
        ]
       */  
 
            })
         })
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35575a5a41464147544575001b051b07">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64060b0b10171016051424514a544a56">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div id="app">
  <div>
       <div class="row">
         <div class="col-sm-6">
         <h5>Wrong result :</h5>
           <div v-for="service in arrayService"  :key="service.id">
             <strong>Id Service:</strong> {{service.service}}
             <br>
             <strong>Format:</strong>
             <div v-for="format in arrayFormat" :key="format.id">
                {{format}}
             </div>
           </div>
            
         </div>
         <div class="col-sm-6">
         <h5>Correct result:</h5>
             <strong>Id Service:</strong> 2
             <br>
             <strong>Format:</strong>
             <br>
             .mp3
             <br>
             .mp4
             <br>
             <strong>Id Service:</strong> 3
             <br>
             <strong>Format:</strong>
             <br>
             .jpg
             <br>
             .png
           <br>
         </div>
       </div>
       <br>
       <br>
       <br>
       <br><br>
       <br>
       <br>
       <br>
       <br>
       <br>
  </div>
</div>

When storing the arrayService, I perform a Parse operation on the format attribute as there is another array containing the formats for each service (refer to comments).

During this Parse process, all the elements (formats) are pushed into an array called arrayFormat.

The issue I am facing is that these elements get stored together instead of separately as intended.

I aim to store each format according to its respective service.

While attempting to display the correct outcome in the HTML view, the ultimate goal is to achieve this functionality using VueJS.

Any suggestions?

Answer №1

There is no need for the arrayFormat array because the necessary data structure is already in the API response.

You can directly iterate through the nested array (service.format):

<div v-for="service in arrayService" :key="service.service">
  ...                      👇
  <div v-for="format in service.format" :key="format">
    {{format}}
  </div>
</div>

new Vue({
  el: '#app',
  data() {
    return {
      arrayService: [{
          service: '2',
          format: [".mp3", ".mp4"]
        },
        {
          service: '3',
          format: [".jpg", ".png"]
        },
      ],
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bddfd2d2c9cec9cfdccdfd88938d938f">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div id="app">
  <div v-for="service in arrayService" :key="service.service">
    <strong>Id Service:</strong> {{service.service}}
    <br>
    <strong>Format:</strong>
    <div v-for="format in service.format" :key="format">
      {{format}}
    </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

Retrieving information from CRM online utilizing the Web API

Recently, I developed a webpage to serve as a survey for end users to provide feedback on the helpdesk technician's performance in resolving tickets. The webpage was constructed using HTML, CSS, JS, and PHP. Currently, the page requires access to two ...

Retrieve the $scope object within an isolated directive

Is there a way to modify a $scope variable from within an isolated directive? I've experimented with the '@, =, &' syntax in the directive scope but haven't been successful. Here's a simplified version of my code: JS app.co ...

Exploring JavaScript-based navigation with Python and Selenium

Here is the URL of the page in question: link. I am trying to navigate pagination with the following HTML markup: <li class="btn-next"> <a href="javascript:ctrl.set_pageReload(2)">Next</a></li> I have written a ...

What is the best way to implement CSS for text within a text area?

Is there a way to make the tags dragged from the dropdown list to a text-area non-editable? Currently, the text in the text-area is editable as shown in the GIF. //TextArea HTML Helper @Html.TextAreaFor(m => m.Formula, new { @class = "form-cont ...

JavaScript now assigns a value of null in place of undefined

When working with JavaScript, it's important to understand that undefined can be reassigned. Because of this, it is recommended to create a self-executing function to ensure that undefined remains undefined. Are there any other values that are loosely ...

Extremely sluggish pagination in JQGrid following the implementation of a filter through the filter toolbar

I've encountered a problem while using jqGrid with LOAD ONCE and client-side paging. The addition of a filter toolbar has significantly slowed down the paging process after applying any kind of filter. $(gridElement).jqGrid({ postData: post, ...

Fixing TypeError: Object #<IncomingMessage> has no method 'flash' in ExpressJS version 4.2

Currently, I am utilizing ExpressJS 4.2 and PassportJS for authenticating local users. Everything seems to be working smoothly except for when attempting to display a failureFlash message. Below is my configuration setup, thank you in advance! ==== Necess ...

Struggling with my jQuery Ajax call, need some help

I am attempting to create an ajax request that will update the content of my select element. Below is the code for my request : $(function() { $("#client").change(function() { type: 'GET', url: "jsonContacts. ...

Prevent selection of specific weekdays in Kendo grid calendar

When editing a record in a Kendo grid with a date field, is there a way to only allow the selection of Monday and disable all other days of the week? ...

Guide to crafting a javascript variable from MySQL through the power of PHP and AJAX

I am not very experienced in working with AJAX and javascript. I am currently trying to pass longitude and latitude values from a MySQL database to javascript, but it doesn't seem to be working as expected. Can anyone help me figure out what I might b ...

Angular with Leaflet and Leaflet AwesomeMarkers error: "Attempting to access 'icon' property of undefined"

I'm attempting to integrate Leaflet Awesome Markers into my Angular 10 project to incorporate Font Awesome icons in my Leaflet markers. However, I'm running into an error when trying to create a L.AwesomeMarker. https://i.sstatic.net/7o81y.png ...

Ways to soften a section of a canvas component?

What is the simplest way to apply a blur effect to a specific portion of my canvas element? I am utilizing the JavaScript 3D Library known as three.js. This library simplifies the use of WebGL. While they offer examples of blur and depth of field effects, ...

performing an action using vuex in a component's method

I am facing an issue where I am trying to dispatch an action and retrieve the values passed into an input field. When I directly dispatch an action on a button, everything works perfectly fine: <button type="button" @click="store.dispatc ...

The method request.getParameter in Servlet may sometimes result in a null

My website utilizes JQuery to make an Ajax call to a servlet. function sendAjax() { $.ajax({ url: "/AddOrUpdateServlet", type: 'POST', dataType: 'json', ...

Tips for accessing a DOM element's ::before content using JavaScript

Is there a way to retrieve the content of a DOM element's ::before pseudo-element that was applied using CSS3? I've attempted several methods without success, and I'm feeling very confused! // https://rollbar.com/docs/ const links = docum ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Add elements from one array into designated positions within another array

Is there a way to extract the days and months from the current week and store it in an array within a specific field of an object? I need to be able to later iterate through this array to display the data. I am unsure on how to achieve this. <div v-for ...

Is the shape of the Shadow in Three.js r76 MeshLambertMaterial unusual?

When using r70, the shadow appears as expected - r70 example (Shadow correct shape) However, with r76, the shadow appears abnormally shaped - r76 example (Shadow abnormally shaped) It is noticeable that the shadows on the MeshLambertMaterial on the groun ...

Exploring the capabilities of AngularJS directives through ng-html2js testing

Many questions have been raised about the ng-html2js plugin, but unfortunately, none of the answers provided were able to solve my specific issue. I meticulously followed the official installation guide and also referenced the example available at https:/ ...

In my handleSubmit function, I'm attempting to prevent my browser from refreshing whenever I send a Post request to the backend

I am encountering an issue with my form where my submit button triggers a handleClick event. When the handleSubmit function is executed, a Post request is made to the backend to update the data and state. However, this action results in the entire page bei ...