Eliminate repeated elements within a JSON dataset to create a consolidated array

Looking to extract unique data from the JSON object below in order to create a result json with a list of questions and their corresponding choices. Any assistance would be greatly appreciated. Thanks in advance..!!

    var data = [
  {
    "category": "sports",
    "question": "Who is the best footballer?",
    "questionType": "text",
    "choices": "Messi",
    "name": "Best Footballer",
    "createdUserId": 1
  },
  {
    "category": "sports",
    "question": "Who is the best footballer?",
    "questionType": "text",
    "choices": "Ronaldo",
    "name": "Best Footballer",
    "createdUserId": 1
  },
  {
    "category": "sports",
    "question": "Who is the best footballer?",
    "questionType": "text",
    "choices": "Ibrahimovic",
    "name": "Best Footballer",
    "createdUserId": 1
  },
  {
    "category": "sports",
    "question": "Who is the top goal scorer?",
    "questionType": "text",
    "choices": "Messi",
    "name": "Best Footballer",
    "createdUserId": 1
  },
  {
    "category": "sports",
    "question": "Who is the top goal scorer?",
    "questionType": "text",
    "choices": "Ronaldo",
    "name": "Best Footballer",
    "createdUserId": 1
  },
  {
    "category": "sports",
    "question": "Who is the top goal scorer?",
    "questionType": "text",
    "choices": "Lewandoski",
    "name": "Best Footballer",
    "createdUserId": 1
  }
];

Target JSON Format

{
    "name": "Best Footballer",
    "category": "sports",
    "createdUserId": "1",
    "questionList": [
        {
            "question": "Who is the best footballer?",
            "questionType": "text",
            "choices": [
                "Messi",
                "Ronaldo",
                "Ibrahimovic"
            ]
        },
        {
            "question": "Who is the top goal scorer?",
            "questionType": "text",
            "choices": [
                "Messi",
                "Ronaldo",
                "Lewandoski"
            ]
        }
    ]
}

Answer №1

Consider using an object named qObj to efficiently locate questions without the need to loop through the entire array.

"use strict";

var data = [{
    "category": "sports",
    "question": "Who is the best footballer?",
    "questionType": "text",
    "choices": "Messi",
    "name": "Best Footballer",
    "createdUserId": 1
}, {
    "category": "sports",
    "question": "Who is the best footballer?",
    "questionType": "text",
    "choices": "Ronaldo",
    "name": "Best Footballer",
    "createdUserId": 1
}, {
    "category": "sports",
    "question": "Who is the best footballer?",
    "questionType": "text",
    "choices": "Ibrahimovic",
    "name": "Best Footballer",
    "createdUserId": 1
}, {
    "category": "sports",
    "question": "Who is the top goal scorer?",
    "questionType": "text",
    "choices": "Messi",
    "name": "Best Footballer",
    "createdUserId": 1
}, {
    "category": "sports",
    "question": "Who is the top goal scorer?",
    "questionType": "text",
    "choices": "Ronaldo",
    "name": "Best Footballer",
    "createdUserId": 1
}, {
    "category": "sports",
    "question": "Who is the top goal scorer?",
    "questionType": "text",
    "choices": "Lewandoski",
    "name": "Best Footballer",
    "createdUserId": 1
}];

var pop = {
    name: "Best Footballer",
    category: "sports",
    createdUserId: "1",
    questionList: []
};
var qObj = {};

data.forEach(function(entry) {

    if (typeof qObj[entry.question] == "undefined") {
        qObj[entry.question] = [];
    }

    qObj[entry.question].push(entry.choices);

});

for (var q in qObj) {
    if (qObj.hasOwnProperty(q)) {
        pop.questionList.push({
            question: q,
            questionType: "text",
            choices: qObj[q]
        });
    }
}

console.log(pop); // JavaScript Object
console.log(JSON.stringify(pop)); // json

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

Express Session Issue Preventing Ajax Call from Functioning

After testing the /temp route directly in the browser and then through an ajax call to the /test route, I noticed a difference in the session information. When accessed directly, the session retains the data added via the /temp route, but when called throu ...

Creating key elements in JavaScript with the push() function

I'm working on a basic shopping cart system using JavaScript (Ionic 2 / Angular). In my PHP code, I have the following: <?php $cart = array( 48131 => array( 'size' => 'STANDARD', 'qty' => ...

Determine if a specific checkbox with a particular id has been selected using JQuery

Looking for assistance on how to determine if a checkbox with a specific ID is checked or unchecked. <input name="A" id="test" type="checkbox" value="A" /> <input name="B" id="test" type="checkbox" value="B" /> <input name="C" id="test1" t ...

Using @GET parameters with Android's retrofit

I have created an interface to fetch weather data from the OpenWeather API for the city of RZESZOW in the country POLAND. How can I pass query parameters for the user to input their desired city name and country in order to get the weather data? public in ...

Manipulating strings in Discord.js

if(msg.content.includes("[mid]")) { let str = msg.content let pokeID = str.substring( str.indexOf("[mid]") + 5, str.lastIndexOf("[/mid") //get the unique-code for a pokemon ); msg.channel.send ...

What is the purpose of the assertEquals() method in JSUnit?

Currently, I am exploring unit test exercises with a HTML5/JS game that I created and JSUnit test runner. The simplicity of the setup impresses me, but I have noticed that even the documentation lacks a clear explanation of what assertEquals() truly does. ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

jQuery does not support iterating over JavaScript objects

Here is the code snippet I am working with: $(obj).each(function(i, prop) { tr.append('<td>'+ i +'</td>' + '<td>'+ prop +'</td>'); }); Intriguingly, the data in $(obj) appears as: Obje ...

Tips for changing the page URL upon click in a Vue.js application

I am currently developing a post board application using Vue.js and I am facing an issue with redirecting the page when a user clicks on each post. To handle this, I have made use of vue-route and axios in my project. Here is a snippet from index.js, ex ...

Popups generated on the fly without any triggers from links

I'm populating a listview with items from localStorage. When a user clicks on a list item, a corresponding popup should appear. I already have a working solution where the popups are displayed upon request. However, this time I am dynamically adding t ...

Utilizing React with an alternative server-side language

I have a small PHP backend for my website and I want to incorporate React on the front end. However, being new to front-end development and React, I am finding this process confusing as most online examples assume a JavaScript backend with Node modules. W ...

Loading google maps markers dynamically with ajax requests

I'm in the process of plotting around 120 markers on a Google Map by utilizing an ajax populated array containing google.maps.LatLng objects Here is my script <script type ="text/javascript"> $.ajaxSetup({ cache: false }); ...

Seamless Integration of Hosted Fields by Braintree

I am currently struggling with setting up Braintree hosted fields on my registration form. Unfortunately, there are significant gaps between the fields which doesn't look appealing. Despite referring to the braintree documentation and guides, I find t ...

How can I construct a Query Builder expression in Laravel that involves selecting from 2 different tables?

I am struggling with translating this SQL query to a query builder syntax: select products.* from orders, json_table( orders.order_summary, "$.products[*]" columns( quantity int path "$.quantity", variant_id int path ...

The functionality of Jquery appears to be malfunctioning on the Drupal platform, although it performs

I've built a jQuery carousel that is fully functional when tested locally, but encounters issues when uploaded to a Drupal platform. Surprisingly, the jQuery functions properly when entered through the Console. Here's the jQuery code: carousel = ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

Clicking on an element triggers the addition of a class, and the newly

Once the page has finished loading, I am able to utilize jQuery to add a specific class in the following way. $(document).ready(function() { $("#parent").click(function(){ $(".child").addClass("active"); }); }) ...

What is causing onbeforeunload to consistently display a dialog box?

I'm facing an issue where my javascript code displays a confirmation dialog even when there is no unsaved data. I have simplified the problem to this bare minimum: window.addEventListener("beforeunload", (e) => { e.returnValue = null; retu ...