Skip to content
Advertisement

Vue How to Merge Two Arrays From Same Object?

I am pulling data from an API that gives me an object of items, each containing a string named correct_answer and an array named incorrect_answers.

I am trying to combine those values within each item, so when I do v-for, it will loop through the answers merged together in one loop. I also want to randomize the order of those answers.

An example of what the object looks like:

JavaScript

Advertisement

Answer

You could 1️⃣spread the incorrect_answers into a new array with correct_answer, and then 2️⃣ attach the result as a new property on the original data. Additionally, 3️⃣ you could shuffle the answers while you’re at it:

JavaScript

This new array could be used as a computed property (e.g., named questions) in your template:

JavaScript

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement