Combining Arrays in Vue: A Guide on Merging Two Arrays from the Same Object

My current task involves retrieving data from an API that provides me with a collection of items. Each item consists of a string labeled correct_answer and an array named incorrect_answers.

I am in the process of merging these values within each item so that when I utilize v-for, it will iterate through the combined answers in a single loop. Additionally, I aim to randomize the sequence of these answers.

Here is an illustration of what the object resembles:

"results": [
    {
      "question": "Where was the Games of the XXII Olympiad held?",
      "correct_answer": "Moscow",
      "incorrect_answers": [
        "Barcelona",
        "Tokyo",
        "Los Angeles"
      ]
    },
    {
      "question": "What is the first weapon you acquire in Half-Life?",
      "correct_answer": "A crowbar",
      "incorrect_answers": [
        "A pistol",
        "The H.E.V suit",
        "Your fists"
      ]
    },
]

Answer №1

let games = [
    {
      "question": "Where was the FIFA World Cup held in 2018?",
      "correct_answer": "Russia",
      "incorrect_answers": [
        "Brazil",
        "Germany",
        "France"
      ]
    },
    {
      "question": "What is the main character's name in The Witcher series?",
      "correct_answer": "Geralt of Rivia",
      "incorrect_answers": [
        "Ciri",
        "Yennefer",
        "Triss Merigold"
      ]
    }
]

let gameAnswers = games.map(item => [item.correct_answer, ...item.incorrect_answers])

console.log(gameAnswers[0])
console.log(gameAnswers[1])

Answer №2

To achieve this, you can follow the below steps:

const newData = data.map(x => {
  const answers = [x.correct_answer, ...x.incorrect_answers]
  x.answers = shuffle(answers)
  return x
})

This modified array can be utilized as a computed property (e.g., labeled as questions) in your template:

<fieldset v-for="q in questions" :key="q.question">
const rawData = {
  "results": [
    {
      "question": "Where was the Games of the XXII Olympiad held?",
      "correct_answer": "Moscow",
      "incorrect_answers": [
        "Barcelona",
        "Tokyo",
        "Los Angeles"
      ]
    },
    {
      "question": "What is the first weapon you acquire in Half-Life?",
      "correct_answer": "A crowbar",
      "incorrect_answers": [
        "A pistol",
        "The H.E.V suit",
        "Your fists"
      ]
    },
  ]
}

new Vue({
  el: '#app',
  data() {
    return {
      rawData: rawData.results
    }
  },
  computed: {
    questions() {
      return this.rawData.map(x => {
        const answers = [x.correct_answer, ...x.incorrect_answers]
        x.answers = shuffle(answers)
        this.$set(x, 'answer', null) 
        return x
      })
    }
  }
})

function shuffle(array) {
  let currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {

    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3543405075071b031b0405">[email protected]</a>"></script>

<div id="app">
  <form action="#">
    <fieldset v-for="(q,i) in questions" :key="q.question">
      <h2>{{q.question}} {{q.answer}}</h2>
      
      <div v-for="a in q.answers" :key="a">
        <label>
          <input type="radio" :name="i" :value="a" @change="q.answer = a">
          <span>{{a}}</span>
        </label>
      </div>
    </fieldset>
  </form>
</div>

Answer №3

Have you tried using the spread operator to merge multiple arrays in JavaScript like this: let merged = [item.correct_answer, ...item.incorrect_answers]?

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

JQuery failing to validate the form

Whenever I try to validate a form by clicking the submit button, it seems to ignore the validation altogether and proceeds to post the entered data to the next page. Below are the validation codes: <script> $(document).ready(function() { $("#re ...

Is it necessary for JavaScript functions to be stored in a separate file in order to be invoked?

Here is the scenario that unfolded: Within a .php file, I had the following form: <form action="/flash_card/scripts/create_user_gate.php" onsubmit="return validateForm()" method="post"> <table align="center"> ...

Looking to compare the values of objects in one array with the values of objects in another array

Within this code snippet, I am attempting to retrieve the id of a variant that aligns with the selected objects const selected = [ { "id": 14 }, { "id": 95 } ] const variants = [ { "id": 1, "option_values": ...

The view "skills.ejs" could not be found in the views directory

Just one month into my full stack program, I am facing a challenge while trying to render index and details pages on a local server. It's been a frustrating experience so far. :) Despite all my efforts and days of troubleshooting, I can't seem t ...

Tips on displaying five bootstrap modal popups simultaneously on a webpage

I'm looking to achieve a specific functionality that involves opening multiple bootstrap modal popups on one page simultaneously without overlapping each other. Specifically, I need a button to trigger the opening of five separate modals each containi ...

Creating a personalized format for Mongoose aggregate results

I am currently utilizing mongodb with mongoose and attempting to replicate this specific format within my callback function. Here is an example: { warning:[ { "_id": "5a8dcdbcadb65b484e888091", "application_name": "teste", "created_at": "2018- ...

Iterating through a string array and an array containing arrays in Ruby

Help Needed with Ruby Code Here's my current challenge: def iterate1 #method definition within the given class @var3 = @var2.split(" ") #splitting a string into an array @var4 = @var3 @var4.each do |i| #iterating through e ...

Guide on utilizing angularjs $q.all() method with a dynamically generated set of promises

I am currently facing an issue with using $q.all() to wait for multiple promises to be resolved. I have created an array of promises and passed it to the all() method, but it doesn't seem to be working as expected. The promises in the array are gener ...

Aggregating various database entries into an array

I want to retrieve data from a MySQL database and store it in an array for comparison. My objective is to compare one variable ($row[0]) with another predefined variable, and based on the result, use the second variable ($row[1]) to perform a new query on ...

Siblings mousedown event propagation

In my HTML code, I have a division that contains multiple image objects with the position set to absolute. Here is an example: <div> <img> <img> <img> <img> </div> The problem arises when the ...

Adjusting Timeout for Specific HTTP Endpoint in NestJS

I recently delved into learning NestJS and I'm curious about how to adjust the response timeout for specific endpoints. One way is to set it on a server level like this: const server = await app.listen(...); server.setTimeout(1800000) Alternativ ...

(Enhancing Angular) Capture HttpResponse errors and seamlessly proceed with the Observable

There's a dropdown text box with type-ahead search functionality. Valid item names prompt the expected list of items in the drop-down menu, while invalid entries trigger a 400 error response from the API. This error is caught by the HttpErrorIntercept ...

Refreshing a Particular JavaScript File in Electron Upon Request

Lately, I've been working on an Electron app that involves storing data in a javascript file. The data needs to be decrypted when the user logs in and displayed, then encrypted again when the user logs out. While logged in, users can add new data to t ...

After updating to the latest npm version, the NodeJS server continues to display the error message "Upgrade Required" when loading pages

After developing a Node project using NodeJS version 5.4.x and NPM version 3.3.12 on Windows, I encountered an issue where the project throws an "Upgrade Required" message (HTTP Error code - 426) upon loading the page after some time of inactivity. To add ...

The requested module cannot be located, were you referring to "js" instead?

I am currently developing a React application using webpack and typescript. I have integrated the dependency react-financial-charts into my project, and it is properly specified in the package.json. Inside the node_modules directory, there are two folders ...

Scope of an array being passed

I have a challenge of passing an array from one external .js file to another. The individual files are functional on their own, however, the issue arises when trying to pass the array from pickClass.js to displayStudent.js and displaying the names along wi ...

Keep the columns at a full 100% height while accommodating dynamic content

Is it possible to have a two-column layout, where one column remains static while the other dynamically generates content, while ensuring both columns are 100% the height of the wrapper? https://jsfiddle.net/t1h4vngv/1/ HTML <div class="wrapper"> ...

What is the best way to display an image upon clicking a button?

I have a <button> element with the rel="example.jpg" attribute. The goal is to have the image load in the #area DIV only after the button is clicked, not during the page load. I have implemented the following code to achieve this: $(document).ready( ...

Transform a string into a property of a JSON object

One of my challenges involves extracting a value from a JSON object called Task, which contains various properties. Along with this, I have a string assigned to var customId = Custom_x005f_f3e0e66125c74ee785e8ec6965446416". My goal is to retrieve the value ...

A guide to combining JSON arrays with identical values in JavaScript

I have a scenario where I need to merge data from two arrays based on the same value of "calleridnum":"0090000163", "uid":"0090000163", Here is the first array: [ { "_id":"55d44fe38879f12e6431c23c", "event":"ConfbridgeJoin", "channel":"SIP/peer_voip301 ...