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

Utilizing navigation buttons to move between tabs - material-ui (version 0.18.7)

I'm currently using material ui tabs and attempting to incorporate back and next buttons for tab navigation. However, I've run into an issue - when I click the back or next buttons, the tabs do not switch. Here is my existing code snippet: ... ...

Stop unwanted scrolling upwards by using jQuery ajax function $.load

I'm currently in the process of creating an ajax chat using jquery and php. Everything seems to be running smoothly except for one issue related to scrolling. Essentially, I've implemented a time-out function that automatically reloads the inner ...

Restricted access to unauthorized URL, potentially due to sub-frame navigation restrictions

I'm having trouble opening the clicked URL in the browser from my application. . Do I need to include something else? ...

In order to ensure a valid JSON for parsing in JavaScript, one must reverse the usage of single quotes and double quotes. This adjustment

Received an API response structured like this: [{'name': 'men', 'slug': 'men'}, {'name': 'women', 'slug': 'women'}] After stringifying: const data = JSON.stringify(resp) " ...

Attempting to dynamically insert a new row into a table using jQuery, with the added condition of limiting the total number of rows to four

I'm facing an issue with a table that has no rows. I want to dynamically add rows by clicking an anchor tag, with a limit of 4 rows. When the limit is reached, I need to display an alert message saying "only 4 rows allowed." However, currently, it kee ...

How can lines from a CSV be filtered to match specific content in a JSON log file?

In my quest to leverage Python scripting on a CSV file, I am aiming to identify and extract line entries from a JSON log file that contain IP and timestamp values. Once identified, these specific JSON log entries will be redirected to another output file. ...

Downloading a zip file using PHP works successfully when initiated directly, but encounters errors when attempted through a web application

I have been working on a PHP script that generates a zip file and allows it to be downloaded from the browser. The download function in the code snippet below: download.php // ensure client receives download if (headers_sent()) { echo 'HTTP head ...

Enabling the apple-mobile-web-app-capable feature prevents SVG touches from registering

Looking to enhance touch functionality on an SVG element. The touch event detection is done using a jQuery-like selector. (Currently utilizing angular JQLite - angular.element()): .on("mousedown touch", function(event) { No problems with recognition of ...

Best practices for bulk inserting sequences in Node.js using MySQL

I have a dataset ready to be inserted into a MySQL database using nodejs. Here is the code I've written: con.connect(function (err) { myArray.forEach((el)=>{ con.query(1stQuery,1stValue,(error,result)=>{ //do something with ...

Is there a way to initiate the server only after webpack has finished bundling all of the bundles

"scripts": { "start": "node server.js", "build": "webpack" }, Is there a way to execute both npm run build and npm start with a single command? "scripts": { "start": " ...

Submitting a PDF document to the server with PHP Laravel through AJAX

Struggling to send a PDF file via AJAX to my server for handling by a PHP script in a Laravel project. The file doesn't seem to be making it to the server. Despite receiving a 200 response in the network, the server is returning 'file not presen ...

Having trouble with sending a JSON post request in Flask?

I have a setup where I am utilizing React to send form data to a Flask backend in JSON format. Here is an example of the code: add_new_user(e){ e.preventDefault() var user_details = {} user_details['fname'] = this.state.first_name user_d ...

Issue encountered while executing tasks in the Gruntfile.js file

Having trouble with Grunt concatenating my CSS files into one named production.css Below is the output I received from the command prompt: C:\Users\josha\Desktop\Repos\AJAX Project - Grunt Test>grunt C:\Users\josha& ...

Ways to deactivate remaining buttons until a function call finishes after selecting one in a react render() function?

In order to prevent the overlap of results when multiple buttons are clicked simultaneously, I need to disable all toggle buttons until one function call is complete, including the reset button. Additionally, I'm looking for a way to display my functi ...

TypeError: Unable to access the 'items' property of a null value

I am currently working on a program and I am facing an issue where I need to access something from the first component in the second component. Can anyone provide assistance on how to properly construct this? Below is a snippet of my code: ...

Contrasting the use of jQuery versus AJAX for updating static page text

While I haven't fully grasped the concept of AJAX yet, my understanding is that it can be beneficial for updating specific parts of a webpage. Does using AJAX only make sense when you require server interaction? I am looking to replace text on a webp ...

Ways to generate data following the integration of Firebase Firestore in Vue.JS

How can I display the orders data retrieved from Firebase in my browser console? See the image link below for reference. https://i.sstatic.net/HPlaC.png This is the code snippet for fetching data from Firebase and displaying it in the console: orders(){ ...

Steps to update the active state in the "reducer" when clicking on elements outside of the "reducer" area

Working with react-redux has presented some challenges for me. I've created multiple reducers such as action, root reducer, active_step reducer, and list_step reducer. One aspect that I find intriguing is the ability to dynamically map and change the ...

What are the steps to downloading a server-generated image with user data from the client using Express?

I am facing a challenge with downloading a server-generated image immediately after it is created. My current approach involves using fetch to send user input data (bypassing HTML forms). Although the image is successfully generated on the server, I am str ...

What is the best way to apply the addClass method to a list element

I've been searching for a solution to this issue for some time now, and while I believed my code was correct, it doesn't appear to be functioning as expected. HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js ...