Utilize a for loop in Vue.js to save a fresh array of objects in a structured format

Trying to achieve the following using Vue:

I have two JSON objects that provide information on languages and the number of inputs per language. Using nested loops, I display all the inputs. My goal is to create an object for each input with additional details (mentioned below).

The first array returns:

 {
    "type": "Faq",
    "fields": [
        "question",
        "answer"
    ]
}

And the second array returns:

[
    {
        "type": "Language",
        "id": 1,
        "name": "Español",
        "active": true,
    },
    {
        "type": "Language",
        "id": 2,
        "name": "English",
        "active": true,
    },
    {
        "type": "Language",
        "id": 3,
        "name": "Francés",
        "active": true,
    }
]

A form needs to be created displaying questions and answers in each language, like:

Snippet example:

new Vue({
  el: '#app',
  data: {
    msg: 'message',
    translationSchemesFaqs: {
      "type": "Faq",
      "fields": [
        "question",
        "answer"
      ]
    },
    languageSelect: [{
        "type": "Language",
        "id": 1,
        "name": "Español",
        "active": true,
      },
      {
        "type": "Language",
        "id": 2,
        "name": "English",
        "active": true,
      },
      {
        "type": "Language",
        "id": 3,
        "name": "Francés",
        "active": true,
      }
    ],
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>
<body>
  <div id="app">
<div v-for="(language, i) in languageSelect" :key="i">
            <h3>{{language.name}}</h3>
            <div  v-for="(translation, index) in translationSchemesFaqs.fields" :key="index">
               <input
               id="input2"
               ref="groupId2"
               tabindex="1"
               class="body2"
               outlined
               required
               :label="translation + ' ' + language.locale"
             />
            </div>
          </div>
          </div>
</body>

JSFiddle link

The entered information should be saved in an array of objects as shown:

[
{
    "value": "",
    "field": "question",
    "language": {
        "id": "1",
        "name": "Español"
    }
},
{
    "value": "",
    "field": "answer",
    "language": {
        "id": "1",
        "name": "Español"
    }
},
{
    "value": "",
    "field": "question",
    "language": {
        "id": "2",
        "name": "English"
    }
},
{
    "value": "",
    "field": "answer",
    "language": {
        "id": "2",
        "name": "English"
    }
},
{
    "value": "",
    "field": "question",
    "language": {
        "id": "3",
        "name": "Francés"
    }
},
 {
    "value": "",
    "field": "answer",
    "language": {
        "id": "3",
        "name": "Francés"
    }
}]

Any suggestions on how this can be achieved?

Answer №1

One approach to achieve this is by setting up mappings within the languages array. Initially, I map the languages array to include fields such as model, with a value key inside each field. This will serve as the model for v-model of the inputs. Subsequently, I establish the computed value savedArrayOfObject which stores the saved array of objects generated from mapping the model again:

new Vue({
  el: '#app',
  data: {
    msg: 'message',
    translationSchemesFaqs: {
      "type": "Faq",
      "fields": [
        "question",
        "answer"
      ]
    },
    languageSelect: [{
        "type": "Language",
        "id": 1,
        "name": "Español",
        "active": true,
      },
      {
        "type": "Language",
        "id": 2,
        "name": "English",
        "active": true,
      },
      {
        "type": "Language",
        "id": 3,
        "name": "Francés",
        "active": true,
      }
    ],
    model: [],
  },
  computed: {
    savedArrayOfObject() {
      return this.model.flatMap(object => ([
        ...object.fields.map(field => ({
          value: field.value,
          field: field.field,
          language: {
            id: object.id,
            name: object.name,
          }
        }))
      ]))
    }
  },
  mounted() {
    // perform these actions after translationSchemesFaqs and languageSelect are available
    this.model = this.languageSelect.map(language => ({
      ...language,
      fields: this.translationSchemesFaqs.fields.map(translation => ({
        field: translation,
        value: null
      }))
    }))
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>

<body>
  <div id="app">
    {{JSON.stringify(savedArrayOfObject)}}
    <div v-for="(language, i) in model" :key="i">
      <h3>{{language.name}}</h3>
      <div v-for="(translation, index) in language.fields" :key="index">
        <input v-model="translation.value" id="input2" ref="groupId2" tabindex="1" class="body2" outlined required :label="translation + ' ' + language.locale" />
      </div>
    </div>
  </div>
</body>

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

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...

Can I change the name of an item in ngRepeat?

When repeating in a view: ng-repeat="item in list" In some scenarios, the 'item' looks like this: { "name": "john", "id": 1 } While in others, it appears as: { "value": { "name": "john", "id": 1 } } Is there a way to rena ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

Is there a way to send a post request containing a base64 encoded image?

I am currently developing an image upload component in Vue.js that includes a custom cropping option. The cropped version of the image is saved in my state as a base64 string, like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAAAAHgCAYAAAB91L6 ...

What is the process for converting a JSON File into an array using javascript?

Hey there, I'm new to programming so please bear with me XD. I've been struggling for 2 days trying to figure this out with no luck. So here's the deal - I have a chart in JavaScript that is pulling data from a file called test.json, which ...

Error: 'fs' module not found in React.js and cannot be resolved

Encountering issues with tatum io v1 + react? Developers have acknowledged that it's a react problem which will be addressed in V2. In the meantime, you can utilize tatum io V1 with node js. I've included all dependencies that could potentially ...

What is the best way to dynamically insert a new row into a table, with each row containing a table heading and column?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="tbl" class="tbl1"> <tr> <th> mobileno </th> <td class='mo' id="mo_0"> </td> ...

The challenge of extracting JSON values and storing them in PHP variables

In my attempt to use an SMS API, I encountered the need to retrieve a message ID. Below is the code snippet of the API: $url = 'https://rest.nexmo.com/sms/json?' . http_build_query( [ 'api_key' => 'xxx&apo ...

In what mysterious way can my variable possess qualities of both an ndarray and a dictionary at the same time?

I am attempting to access my GloVe vectors for a machine learning model without the need to reload the model each time. To achieve this, I want to store the glove_model dictionary in a json file so that it can be easily loaded elsewhere after its initial c ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

Continuously encountering errors while deserializing JSON objects in C#

I need help deserializing my json data. The json code is stored as a string and includes various objects like post_id, user_id, message, etc. { "post_id":13, "thread_id":9, "user_id":1, "username":"Username", "post_date":1496439611, "message": ...

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

How can I use ngx-editor to insert an HTML block at the current cursor position by clicking a button?

I am currently using ngx-editor within Angular 7. My goal is to insert HTML at the cursor's position upon clicking on parameters from a list. The current view displays how the parameter is appended when clicked, as shown in the image attached . My de ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

Navigating through the year selection with your keyboard

By default, a dropdown menu containing years allows for keyboard navigation. For example, if you type in 1992 while the dropdown is selected, it will automatically move to that specific year option. I am curious to know if there is a way to activate a two ...

What could be causing the <img src= ' '/> tag to malfunction in Express?

While learning about HTML, I noticed that simply using img src="...." worked fine. However, when working with Express, the same code did not work! The documentation mentioned that I needed to place the images in a folder named public, require(&ap ...

Implementing script loading within the Angular scope

I'm attempting to load a custom script from the database based on client-side logic. I am having trouble figuring out how to make it function properly. Here is my controller code: 'use strict'; angular.module('youshareApp') . ...

Updating a JSON file with new data in Dart

I am working on a Flutter project where I have a Json file containing user data in an array. While I am able to read this data, I now want to add another user from the textfield input in my app. Can someone guide me on how to achieve this? Thank you in adv ...

Tips for formatting a lengthy SQL query in a Node.js application

Currently, I am facing a challenge with a massive MySQL select query in my node.js application. This query spans over 100 lines and utilizes backticks ` for its fields, making me uncertain if ES6's multi-line string feature can be used. Are there any ...

What is the proper way to incorporate a ref within a class component?

I am encountering an issue with my class component. I'm wondering if there is a comparable feature to useRef() in class components? Despite several attempts at researching, I have yet to find a solution. ...