Obtain the shared value between two data entries within a Vue array

In my Vue.js data, I have two records with the same question id. I want to select both record options and only one of the questions.

[
  {
     "id":7,
     "question_id":102,
     "option":"true",
     "is_correct":"1",
     "question":"This is a question",
     "option_type":1
 },
{
     "id":8,
     "question_id":102,
     "option":"false",
     "is_correct":"0",
     "question":"This is a question",
      "option_type":1
}
]

Expected outcome After executing the solution, I expect the following result:

    question_id:[
        { 
            "id":7,
            "option":"true",
            "is_correct":"1",
            "question":"This is a question",
            "option_type":1
         }
         { 
            "id":8,
            "option":"false",
            "is_correct":"0",
            "question":"This is a question",
            "option_type":1
         }
       ]

Attempted Approach

   <label class="form-control" v-for="question in response" :key="question.id" track-by="question_id">{{ question.question }}</label>
    <div v-for="option in response" :key="option.id">
    <input type="radio" name="pickedAnswer" id="option" :value="option.id">
    <label for="option" class="ml-3">{{option.option}}</label><br>                                    </div>

I will be waiting for your comments. Thank you.

Answer №1

Here is one way to accomplish this using plain JavaScript:

let data = [
  {
     "id":7,
     "question_id":102,
     "option":"true",
     "is_correct":"1",
     "question":"This is a question",
     "option_type":1
  },
  {
     "id":8,
     "question_id":102,
     "option":"false",
     "is_correct":"0",
     "question":"This is a question",
      "option_type":1
  }
]

const groupByQuestionId = function(data, key) {
  return data.reduce(function(result, element) {
    (result[element[key]] = result[element[key]] || []).push(element);
    delete element[key];
    return result;
  }, {});
};

console.log(groupByQuestionId(data, 'question_id'));

Answer №2

If I grasp your objective correctly, the use of Vue may not be necessary. Vue v-for and HTML are typically used to display data rather than manipulate it. My recommendation would be to create a function (either within the created() hook or mounted(), depending on where your data originates) and implement groupBy to gather all the necessary information.

There are two common approaches to achieving this: utilizing lodash or leveraging native ES6 features. Below, I will outline both methods:

 // ES6 

 resp.reduce((acc, value) => {
   acc[value.question_id] = [...acc[value.question_id] || [], value]
 return acc;
}, {});

// { 102: [{ id: 7, ...}, { id: 8, ...}] } 

You can employ a reduce function to construct a new object with question_id as the key and the grouped questions as the value.

Lodash

// Lodash

_.groupBy(a, 'question_id')

// { 102: [{ id: 7, ...}, { id: 8, ...}] } 

While using Lodash is more straightforward, keep in mind that you will need to install the lodash library (which might not be ideal for just one function, given the size of lodash). If you decide to go with Lodash, I recommend reading an article like The correct way to import lodash for guidance on importing lodash without impacting your build process too heavily.

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

What comes after fetching data with axios but before the webpage is rendered?

Struggling to dynamically render my DOM based on data retrieved from an axios get request. The timing seems off as there is a delay between the request and receiving the data. Essentially, I need to display a 'cancel' button if there is informati ...

Tips for creating a vertical scrollbar within a row component

Is there a way to create a scrollable parent v-row with a child v-row overflowing with content so that I can nest another v-row inside the v-col and ensure it remains within the scroll element? <v-row> <v-col> <v-row> <p ...

Error: Combining objects that are not defined is not allowed

While running $ quasar dev on my Vue project, I encountered the following error: ~/project/node_modules/webpack-merge/dist/index.js:63 throw new TypeError("Merging undefined is not supported"); ^ [ TypeError: Mer ...

The UglifyJsPlugin in Webpack encounters an issue when processing Node modules that contain the "let" keyword

Below is the code snippet from my project which utilizes Vue.js' Webpack official template: .babelrc: "presets": [ "babel-preset-es2015", "babel-preset-stage-2", ] webpack.prod.config.js new webpack.optimize.UglifyJsPlugin({ compress: { ...

What could be causing Vue Material dialogs to frequently slide off the screen?

I am currently utilizing a dialog feature from Vue Material (). After following the link and opening the first custom dialog on the page, I noticed that it tends to shift towards the top left of my screen, making only a portion of the dialog visible. This ...

Error 405 (Invalid Method) in VueJs: You are not allowed to use

I have a route defined in the group with 'prefix'=>'admin' in web.php Route::post('/slideUpdate/{id}','SlideController@postSlideUpdate') In Add.vue, I am calling the update() function in methods axios.patch(`/a ...

VueJS in collaboration with Quasar framework

Incorporating VueJS with Quasar framework, I created a data table. Here is my implementation: <template> <div class="q-pa-md"> <q-table title="Task List Of The Day" :columns="columns" row-key="name" :pagination ...

What is the preferred approach: modifying the Pinia state within actions or directly within the component?

One challenge I've encountered involves a function within my Pinia store: async function getCurrentUser(){ let user: User | undefined = undefined; if (auth.currentUser?.uid) { user = await getUserById(auth.currentUser.uid) state.va ...

"When the value is false, use the Vue binding to apply a specific

My challenge involves managing a website that is designed to receive boolean values and store them in an array where the key represents the ID and the value represents the boolean. For example: policiesActive[ "2" => false, "3" => false] The w ...

Using the Gmail API to retrieve the access token details by extracting the "code" parameter from the URL of a pop-up window

I am currently in the process of authenticating Gmail using OAuth2 for my web application. Upon receiving a URL from the server, the client opens a pop-up window with the following code: var win = window.open(data.google_oauth_url, `<h1>Gmail ...

Navigating through property objects in Vue: accessing individual elements

I am a newcomer to Vue and after reviewing other questions on this platform, I am struggling to figure out how to pass an object to a child component and reference individual elements within that object. My goal is to have access to all elements of the obj ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

What is the process for calculating data from an external document?

Within main.js: import player from './package/Player'; Vue.use(player); ... new Vue({ el: '#app', player, Now in player.js: export default function (Vue) { let isPlaying = true; Vue.player = { changePlaying(){ ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

Encountering the "Module not found" error message stating "Error: Unable to locate '@uidu/ckeditor5-tokenizr' when trying to import an npm package that I have just installed."

Recently, I added the package @uidu/ckeditor5-tokenizr to my project. It is located in node_modules/@uidu/ckeditor5-tokenizr. However, when trying to import it using import tokenizr from '@uidu/ckeditor5-tokenizr'; within my Vue Components secti ...

The second parameter of the Ajax request is not defined

Having an issue with my Ajax request in Vue.js where the second parameter is logging as undefined in the console. I've been trying to fix this problem but haven't found a solution yet. This is the code snippet for $.ajax(): //$.ajax() to add ag ...

The use of script src with vue.js is causing issues

I am looking to move my Vue code into an external .js file. Since I am new to Vue, I am trying to keep it simple without using webpack. However, I have encountered an issue where Vue does not work when using the script src tag in the html file. For instanc ...

how to use $emit to modify a computed property in VueJS

I have a form with multiple components for input fields, each containing another component for displaying errors. Here is the code: // Input component <template></template> <script> import Store from '../../store' exp ...