Transforming JSON format to another JSON format using AngularJS

I am in the process of setting up a questionnaire using angularjs. I have an array of responses that looks like the following, and I need to convert this object array into JSON format. How do I go about converting an object array into JSON format?

 
        var response=[
            {"questiongroup":1,"question":1,"response":"response1"},
            {"questiongroup":1,"question":2,"response":"response2"},
            {"questiongroup":1,"question":3,"response":"response3"},
            {"questiongroup":1,"question":4,"response":"response4"},
            {"questiongroup":1,"question":5,"response":"response5"},
            {"questiongroup":2,"question":6,"response":"response6"},
            {"questiongroup":2,"question":7,"response":"response7"},
            {"questiongroup":2,"question":8,"response":"response8"},
            {"questiongroup":2,"question":9,"response":"response9"},
            {"questiongroup":2,"question":10,"response":"response10"}
        ];
    

Desired Output:


        {
            "questiongroups": [
                {
                    "questiongroup": 1,
                    "question": [
                        {"question": 1, "response": "response1"},
                        {"question": 2, "response": "response2"},
                        {"question": 3, "response": "response3"},
                        {"question": 4, "response": "response4"},
                        {"question": 5, "response": "response5"}
                    ]
                },
                {
                    "questiongroup": 2,
                    "question": [
                        {"question": 6, "response": "response6"},
                        {"question": 7, "response": "response7"},
                        {"question": 8, "response": "response8"},
                        {"question": 9, "response": "response9"},
                        {"question": 10, "response": "response10"}
                    ]
                }
            ]
        }
    

Answer №1

After contemplating various approaches, I arrived at the most efficient solution.

I condensed the response into an object structure where the question groups serve as identifiers for arrays. To customize the output, I mapped the keys to create an array and compiled the object with the values corresponding to question groups.

var response=[{"questiongroup":1,"question":1,"response":"response1"},
                     {"questiongroup":1,"question":2,"response":"response2"},
                     {"questiongroup":1,"question":3,"response":"response3"},
                     {"questiongroup":1,"question":4,"response":"response4"},
                     {"questiongroup":1,"question":5,"response":"response5"},
                     {"questiongroup":2,"question":6,"response":"response6"},
                     {"questiongroup":2,"question":7,"response":"response7"},
                     {"questiongroup":2,"question":8,"response":"response8"},
                     {"questiongroup":2,"question":9,"response":"response9"},
                     {"questiongroup":2,"question":10,"response":"response10"}];

var questiongroups = response.reduce(function(groups, question){
  var group = groups[question.questiongroup] || [];
  group.push({
    question: question.question,
    response: question.response
  });

  groups[question.questiongroup] = group;
  
  return groups;
}, {});

questiongroups = Object.keys(questiongroups).map(function (key) {return {questiongroup: key, question: questiongroups[key]}});
var object = {
  questiongroups: questiongroups
};

console.log(object);

Answer №2

let answers=[{"group":1,"question":1,"ans":"response1"},
                     {"group":1,"question":2,"ans":"response2"},
                     {"group":1,"question":3,"ans":"response3"},
                     {"group":1,"question":4,"ans":"response4"},
                     {"group":1,"question":5,"ans":"response5"},
                     {"group":2,"question":6,"ans":"response6"},
                     {"group":2,"question":7,"ans":"response7"},
                     {"group":2,"question":8,"ans":"response8"},
                     {"group":2,"question":9,"ans":"response9"},
                     {"group":2,"question":10,"ans":"response10"}];

let finalResult = {
"groups": [],
}

let group = {
"group": 1,
  "questions": []
}

for (let j in answers) {

if (answers[j].group != group.group) {
  finalResult.groups.push(group);
    group = {
    "group" : answers[j].group,
  "questions": []
    };
  }
  
  let info = {
    "question" : {
      "question" : answers[j].question,
      "ans" : answers[j].ans
    }
  }
  
  group.questions.push(info);
}

finalResult.groups.push(group);

console.log(finalResult);

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

Retrieve a list of applications in JSON format from your Heroku account

Building a Node/Express app to showcase my portfolio. I found an interesting CLI command that allows me to view a JSON list of my apps and their properties directly in the terminal: https://devcenter.heroku.com/articles/using-the-cli#app-commands Now, I& ...

What is the process for establishing a key on the request header to authenticate in Node.js?

I am a novice in the world of nodejs. My current project involves creating a basic server that writes JSON data to a CSV file. However, I have encountered a stumbling block: For authentication purposes, the request header must include an “appKey” para ...

Turn off auto-suggestion feature on the iPad and iPhone keyboard using JavaScript

I'm facing a challenge where I want to turn off the predictive suggestions and autocorrect feature on the iPad keyboard. This image is just for display purposes and not from my actual project. I need to hide the highlighted suggestion bar, and I am u ...

Steps for including a map in a property file for JavaScript parsing

When a checkbox is clicked, a new series of checkboxes will be displayed. The details for these checkboxes are fetched from a database. However, I now need to have certain checkboxes pre-checked based on the user's selection. Since I can't store ...

Top method for independently scrolling overlapping elements in both the x and y directions

Sorry if this is repeating information. I have a structure of nested divs like this: -container -row In order to enable scrolling without the default scrollbar appearing, each container and row has an additional container. My goal is to be able to scrol ...

What is the best way to use jQuery to find and select an "a" tag that links to a file with a specific

My goal is to select links that have different types of files using jQuery: jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=" ...

Step-by-step guide on integrating async and await functionality into Vuetify rules using an ajax call

I'm currently using Vuetify form validation to validate an input field, and I'm exploring the possibility of making an ajax get call await so that I can utilize the result in a rule. However, my attempts at this approach have not been successful! ...

Error message 'Object doesn't have support for this property or method' is triggered by a basic JSON object

Recently, I developed a compact framework for loading resources asynchronously (hyperlink). The framework functions properly in modern browsers such as Opera, Chrome, and Firefox. However, when testing it in IE8, the code fails to execute. Internet Explor ...

Having trouble muting the audio on my Vue audio player

I'm facing some challenges with muting the audio within my vue app. I have a list of songs that can be played, paused, shuffled, etc., but I can't seem to get the mute function working. Here's what I have in the JavaScript: mute() ...

Custom Typescript type that runs concurrently with the base type is disregarded

Assumption: When creating a custom type that mirrors an existing type, the expectation is for variables assigned to that type to maintain it and not default back to the base type. In the function f provided below, the expected return type should be Dog ins ...

Using postMessage to communicate with the localstorage of an iframe from a separate domain

I have a question regarding the challenges of using localStorage for performance reasons and any potential workarounds. From what I gather, once a reference to localStorage is detected on a page (at compile time?), it blocks the thread to read data from di ...

Focus event in IE does not always work as expected after an ajax request is

Our current focus is on supporting IE8 exclusively. An ajax call retrieves data from the server, replaces the HTML in a container div with the response, and then attempts to focus on an element within the response. However, there seems to be inconsistenci ...

"Empty array conundrum in Node.js: A query on asynchronous data

I need assistance with making multiple API calls and adding the results to an array before returning it. The issue I am facing is that the result array is empty, likely due to the async nature of the function. Any help or suggestions would be greatly appre ...

Is it possible to copy text from an iframe to the clipboard?

I have encountered an issue in my React app where I am trying to copy text from a card when the user clicks on it. The app displays multiple cards by looping through an array, so there can be any number of cards (n). The problem arises because the React a ...

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

Are your JavaScript scripts causing conflicts?

My bootstrap Carousel was working perfectly fine until I added a script to modify the navigation bars. The original script for the Carousel looked like this: <script> !function ($) { $(function() { $('#myCar ...

Exploring JSON data using Jinja2 in Python

I received a JSON from an API, as shown in the image below: This is how my views.py file looks like: def index(request): movieData = requests.get('https://api.themoviedb.org/3/search/movie?query=Ishtar&api_key=....').json() return ...

Tips for implementing a repeater item to function beyond the ng-repeat directive

Recently, I decided to play around with AngularJS and now I seem to be facing a small issue with ng-class. Specifically, I'm attempting to change the color of an awesome font icon. <div ng-controller="MyCtrl"> <i ng-class="{'test': ...

Automatically load content using AJAX when scrolling within a HTML5 segment

Recently, I've been developing a website that dynamically loads new content from a MySQL database as the user scrolls. However, I've encountered an issue where the new content is loaded even with minimal scrolling, rather than only when reaching ...