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

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

Seeking clarification on how the Typescript/Javascript and MobX code operates

The code provided below was utilized in order to generate an array consisting of object groups grouped by date. While I grasped the overall purpose of the code, I struggled with understanding its functionality. This particular code snippet is sourced from ...

Guide to integrating jssor into an AngularJS application

Struggling to integrate jssor with angularjs, it seems to be failing because jssor is being initialized before angularjs, causing the ng-repeat elements to not resolve correctly. <div id="slider1_container"> <div u="slides"> <!-- Th ...

Continuously looping through the function based on availability in Symbol ES6

When using the ES6 Symbols iterator, I found that I needed to call the next function each time to print the next item during iteration. Below is the code snippet: var title = "Omkar"; var iterateIt = console.log(typeof title[Symbol.iterator]); var iter ...

What methods work best for retrieving non-API data in Next.js when deploying on Vercel?

Before rendering my application, I am working on fetching my data. Luckily, Next.js offers a method called getStaticProps() for this purpose. Currently, I am utilizing the fs module to retrieve data from a json file in my local directory. export async fun ...

Dealing with an Ajax request that returns a file or partial HTML in the event of an error - what is the best approach?

Imagine a scenario where we are engaged in a dialogue with certain settings. Upon clicking the "OK" button in the dialogue, the settings are transmitted to a controller function through an AJAX call. This call may either yield a downloadable file or an err ...

How about I visit the campgrounds/edit page for a change?

In this get route, the previous link it was redirected from is stored in the req.session object under returnTo. Once redirected, it goes to the /login and we are able to view the object in the console. router.get('/login', (req, res) => { ...

The onclick button in React is not triggering

I am currently working on a component that processes card clicks and redirects users to a previous route, however, the OnClick function does not seem to be functioning properly. I'm trying to pinpoint where I might be going wrong. function Character ...

After attempting to log in, the loggedIn state changes back to false, preventing me from accessing the guarded route

Protecting my routes with state: { loggedIn: false }, aims to trigger the action this.$store.dispatch('setLogin') from my Login.vue component, which updates the state of loggedIn to true. A navigation guard is in place to block access to Login.vu ...

Storing information in a database using Phantomjs

My app is built on phantomjs and here's how it currently operates: 1. A php script retrieves data from my postgres database as an array, 2. The array of data is then passed as an argument to a shell_exec command running a phantomjs script, 3. Phantomj ...

What is the method for producing an li and anchor tag using a list object?

Here is the response I received from my web service, and now I need to transform it into a list item tag: {"d":[{"name":"ttt","url":"bbbb"},{"name":"uuu","url":"ppp"}]} How can I create li tags based on the above output? This is the desired format for t ...

Smooth polygons in a Three.js model

After implementing the following code: var manager = new THREE.LoadingManager(); manager.onProgress = function ( item, loaded, total ) { console.log( item, loaded, total ); }; var texture = new THREE.Texture(); var loader = new THREE.ImageLoader( ...

Guide to creating a unit test for canActivate guard in Angular routing

Seeking guidance on writing a unit test for angular routing with the canActivate guard. Encountering an error when using the guard on routes, but no error is thrown without it. Would appreciate a suitable example along with an explanation. app-routing.mod ...

Transform the JSON object into collections that support the IEnumerable interface

Is there a way to convert a JSON object into Collections that implement IEnumerable so they can be used in a foreach loop? ERROR: "foreach statement cannot operate on variables of type 'Attributes' because 'Attributes' does not contain ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

Efficiently organizing items within a list on Ionic

Currently, I have an ion-list structured as follows: <ion-list *ngFor = "let chat of Chats"> <ion-item (click) = "openChat(chat.id)"> <ion-label> <h2> {{chat.username}} </h2> ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

Performing a one-way analysis of variance (ANOVA) with multiple groups using either MATLAB

I am analyzing 4 classes of data with dimensions (72, 22, 22) and I want to perform ANOVA1 for each pair within the (22, 22) in those classes. For instance, my goal is to select pairs like (2, 3) from each class and conduct ANOVA for every pair across al ...

Transfer the output to the second `then` callback of a $q promise

Here is a straightforward code snippet for you to consider: function colorPromise() { return $q.when({data:['blue', 'green']}) } function getColors() { return colorPromise().then(function(res) { console.log('getColors&ap ...

Backbone sorting is specifically designed for organizing views within the framework

As I work on creating a sorting function in backbone, I have come across recommendations to use views to listen for changes in collections and then render the views once the collections are sorted. However, this approach does not suit my needs for two main ...