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

Issues with rendering in Next.jsORErrors encountered during rendering

Encountering errors while attempting to build my page using "Yarn Build" Automatically optimizing pages ... Error occurred prerendering page "/design/des". More details: https://err.sh/next.js/prerender-error: Error: Cannot find module './des.md&apos ...

Click to start viewing the video

I'm attempting to have a video play when clicked, either on the video itself or around the video. There are multiple videos on the page and I've tried various solutions including the script below which didn't work. $('video'). ...

Vue.js Element UI form validation - showcasing errors returned by server

Utilizing Vue.js and Element UI libraries for my current project, I have implemented front-end validation with specific rules. However, I now also require the ability to display backend errors for the current field. When the form is submitted and an error ...

Material UI does not support the inline attribute for applying CSS properties

Trying to adjust the CSS for Material-UI When setting the width, everything works fine. However, when attempting to set display inline, an error occurs ---> "inline is not defined" Can anyone provide guidance on how to resolve this issue? Sharing my cod ...

Dividing the JSON dataset into smaller segments

Here is an example demonstrating how to split the JSON data: var data = [ { BankName: 'SBI', IFSC: 'SBIN0002688' }, { BankName: 'ICICI', IFSC: 'ICIC0003931', MICR: '500229094'}, { BankName: 'RBI ...

Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up. Validator: import { DataService } from './services/da ...

Error handling in Mongoose callback functions

Currently, I am delving into nodejs, express and mongoose. A question has arisen in my mind regarding the findOne function used to fetch a document from the database. Typically, it is utilized like this: Product.findOne({_id: req.params.id},function(erro ...

Every time I attempt to reuse my components, they keep piling up on top of each other

I'm facing an issue where I need to reuse components I've created multiple times while rendering dynamic content. However, when I attempt to render them, they end up stacking on top of each other in the same position. Each time I render ...

Unraveling JSON in Golang

I'm struggling to identify the issue in my code for decoding this JSON. When I try, it results in an empty struct. You can access the Go playground here: http://play.golang.org/p/K8WznLT5M0 package main import ( "encoding/json" "fmt" ) type ...

Threejs: Illuminating the spotlight with visibility

For my current project, I am attempting to create a visible spotlight similar to the one used by Batman. I want that cone of light that pierces through the night sky. Unfortunately, I do not have any experience with graphics or 3D design, so I am strugglin ...

Is it possible to display a title tooltip only when the CSS ellipsis feature is active in a React component?

Issue: I am trying to find a neat solution to display a title tooltip on items that have a CSS ellipsis applied, within a React component. Approaches Attempted: I created a ref, but it only exists after componentDidUpdate. Therefore, I force an update w ...

Having trouble iterating through a grouped array in JavaScript?

Regrettably, I am facing issues once again with my grouped messages. Although I have received a lot of assistance from you previously, I still find myself struggling and hesitant to ask for help again. Initially, my objective was to group messages based o ...

Displaying the HTML code for a dynamically generated table

Can the generated HTML code be retrieved when dynamically creating a table using v-for loops in Vue? <table> <tr> <th colspan="99">row 1</th> </tr> <tr> <th rowspan="2">row 2< ...

Retrieve the user ID by utilizing the phonegap login feature integrated with Facebook

I'm working on a feature that lets users upload photos to my server once they log in using their Facebook credentials. I'm currently using the phonegap facebook plugin for Android. How can I retrieve their unique user ID from the Facebook SDK? Al ...

What is preventing me from using .bind(this) directly when declaring a function?

Consider the code snippet below: function x() { this.abc = 1; function f1() { alert(this.abc); }.bind(this) var f2 = function b() { alert(this.abc); }.bind(this); } I am curious about how to make the "this" of the out ...

To clear the previous result of an AJAX call in JavaScript, reset the function or variable

I encountered a problem previously, and now another issue has come up. It appears that the previous result from my ajax JavaScript is still being displayed, and I need to prevent that from happening. I've tried deleting the variable, setting it to und ...

Simple steps to convert Redux state to Redux Persist with the help of 'combineReducers' function

I'm facing a challenge trying to implement Redux-Persist with my Redux state, particularly because I am using combineReducers. Here is the structure of my store: import { createStore, combineReducers } from 'redux' import { usersReducer } fr ...

Transmit a message from the background.js script to the popup window

Currently, I am looking to integrate FCM (Firebase Cloud Messaging) into my chrome extension. After conducting thorough research, I have discovered that the most efficient way to implement FCM is by utilizing the old API chrome.gcm. So far, this method has ...

Understanding how jQuery ready function works is essential in ensuring proper

My question is regarding an object I have created: function myObj (){ this.name = "noName"; } myObj.prototype = { init: function(){ console.log(this); this.setName(); }, setName: function(){ this.name = "object name"; } } var ob ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...