Combining Data Structures in Javascript for Visualization in VueJS

Welcome to my first time asking a question.

I am currently working on integrating data from two different API endpoints served by a Django Rest Framework backend and displaying it using VueJS on the frontend.

The main issue I'm encountering is how to combine sections and questions from a questionnaire with their corresponding answers. The questionnaire information comes from one endpoint, while the answers come from another. Here's a snippet of the data:

Data for Sections & Questions

{
    "survey_id": 2,
    "survey_name": "My Survey",
    "instructions": "Instructions.",
    "other_header_info": ""
    "section": [
        {
            "section_id": 2,
            "section_name": "Section Name",
            "section_title": "Section Title",
            "section_instructions": "Some Instructions",
            "section_required_yn": true,
            "question": [
                {
                    "question_id": 2,
                    "question_name": "Question One.",
                    "question_subtext": "None.",
                    "answer_required_yn": true,
                    "input_type_id": {
                        "id": 3,
                        "input_type_name": "Dropdown"
                    },
                    "option_group_id": "1 - 10",
                    "allow_multiple_option_answers_yn": false
                },
{
            "section_id": 3,
            "section_name": "Another Section",
            "section_title": "Section Title",
            "section_instructions": "Section Instructions",
            "section_required_yn": true,
            "question": [
                {
                    "question_id": 10,
                    "question_name": "Another question to be answered",
                    "question_subtext": "None.",
                    "answer_required_yn": true,
                    "input_type_id": {
                        "id": 3,
                        "input_type_name": "Dropdown"
                    },
                    "option_group_id": "1 - 10",
                    "allow_multiple_option_answers_yn": false
                },

Answers Data

"results": [
    {
        "id": 100,
        "answer_numeric": 4,
        "answer_text": null,
        "answer_yn": null,
        "answer_group": "4-ojepljuu",
        "question_id": 2,
    },
    {
        "id": 101,
        "answer_numeric": 1,
        "answer_text": null,
        "answer_yn": null,
        "answer_group": "4-ojepljuu",
        "user_id": 4,
        "question_id": 5,
    },

I understand that I need to match the 'question_id' fields from both datasets. However, I'm struggling with how to achieve this.

My goal is to create a new dataset where answers are appended to the questions. Additionally, I aim to provide flexibility as I have various survey types with different numbers of sections and questions.

I want to organize the data into sections to customize the frontend views accordingly.

I've attempted to loop through sections and questions following an example I found here: Merge two array of objects based on a key, but haven't made much progress.

Since I'm still relatively new to this, any help, guidance, or even a functioning example would be highly appreciated.

Update: I've made some progress by creating a test function that updates the section/question object with dummy data.

var a = this.answers;
var s = this.section;

var newObj = { answer_text: "test1", answer_numeric: "test2" };
for (var idx3 = 0; idx3 < s.length; idx3++) {
   for (var idx4 = 0; idx4 < s[idx3].question.length; idx4++) {
      Object.assign(s[idx3].question[idx4], newObj);
      }
   }

Now, each question object within every section includes key/value pairs for 'answer_text' and 'answer_numeric'.

The next challenge is to retrieve matching answer data by comparing the 'question_id' in the answer object with the same in the question object.

Any suggestions?

Answer №1

To optimize the storage of data, I recommend using a dictionary instead of an array for storing 'results':

var resultsToDict = function (results) {
  var dict = {};
  results.forEach(r => dict[r.question_id] = r);
  return dict;
};
results = resultsToDict(results);

With this approach, you can easily display questions along with their answers in your template:

<div v-for="question in section.questions" :key="question.question_id">
  <p>Question: {{question.question_name}}</p>
  <p>Answer: {{answers[question_id].text}}</p>
</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

Shifting elements within Phoria.js

I'm currently working on a game where a ball bounces and falls into a randomly placed bin. I'm wondering if there's a way for the ball to jump and land based on the dynamic coordinates of the bin. If I have knowledge of the direction and dis ...

v-rating is failing to show the correct value retrieved from the Firestore database

Looking for some assistance here. I am trying to set up a contractor's performance rating system where we can rate the contractors using vuetify v-rating and save the ratings into firebase firestore. I have been able to update the rating and save it ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

The manner in which sessionStorage or localStorage is shared between different domains

I am looking to persist data across different domains using sessionStorage or localStorage. How can I achieve this? The data needs to be shared between a Vue project and a React project. English is not my strong suit, so I hope you are able to understand ...

Managing the "Accept Cookies" notification using Selenium in JavaScript

As I use Selenium to log in and send messages on a specific website, I am faced with a cookie popup that appears each time. Unfortunately, clicking the accept button to proceed seems to be quite challenging for me. Here is an image of the cookie popup Th ...

Struggling with Vue 2's v-model not properly binding data and potentially removing properties?

I am currently dealing with a situation where I have a select element bound to nested data: <select class="form-control" v-model="user_profile.sport.sport_id"> <option v-for="sport in sport_information.sports" :value="sport.sport_id"> ...

Can a linked checkbox be created?

Is it possible to create a switch type button that automatically redirects to a webpage when turned on by clicking a checkbox? I'm working on implementing this feature and would like to know if it's feasible. ...

Unable to detect hover (etc) events after generating div elements with innerHTML method

After using the code below to generate some divs document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>'; I am encountering an issue with capturing hover events: $(".colorB ...

When an array is returned asynchronously in Nuxt, it displays "__ob__: Observer" as the result

I have been working on implementing this code, but I am facing an issue where the array is returning '__ob__: Observer', which I find confusing. I was expecting the array to return with a data type of an array, but that does not seem to be the ca ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

Is there a way I can invoke my function prior to the form being submitted?

For the last couple of days, I've been struggling to make this code function properly. My goal is to execute a function before submitting the form to verify if the class for each variable is consistent. You can access my code here. Any assistance you ...

Exploring shader file content within three.js with the help of jQuery

I am trying to retrieve the content of a string that I have imported using HTML from within another script. To include the text file in question in the html file: <script src="shaders/fragmentshader.fs" id=fragmentshader></script> After impo ...

A guide on incorporating a Java loop with Selenium automation

// Searching and deleting process driver.findElement(By.cssSelector("input[type='search']")).sendKeys("Diversification Rule Template"); driver.findElement(By.className("delete-template")).click(); Alert alert = driver.switchTo.alert(); Thread. ...

The persistent Bulma dropdown glitch that refuses to close

In the project I'm working on, I have implemented a Bulma dropdown. While the dropdown functions correctly, I am facing an issue when adding multiple dropdowns in different columns with backend integration. When one dropdown is open and another is cli ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...

The blast.js example runs flawlessly on CodePen but encounters issues when run locally

I recently discovered blast.js and am encountering a problem when trying to run an example. The example functions perfectly on codepen, but fails to work on my local machine. The console is showing the following warning and error message. Any assistance fr ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

"Redirecting using parameters upon pressing the enter key: A step-by-step guide

I've been pondering about the best way to redirect to a specific site while including query parameters in the URL. <input id="query" name="query" placeholder="Search" type="input" > I have experimented wi ...

Divergence in results: discrepancy found in the outputs of nodejs crypto module and tweetnacl.js

Consider this code snippet in nodejs: import crypto from 'crypto'; const pkey = `-----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIJC52rh4PVHgA/4p20mFhiaQ/iKtmr/XJWMtqAmdTaFw -----END PRIVATE KEY-----`; // placeholder key function sign_message(m ...

Develop a personalized mapping API with a unique image integration for website navigation

Currently, I am in the process of developing a website for my university that will allow users to easily locate all available free food options on campus. My goal is to create a platform where food providers can register their events, have them saved in a ...