Reorganizing data with JSON using JavaScript

I have a JSON data that I am parsing with NodeJS and I need to restructure it into a different JSON format. The original JSON includes multiple "pages" objects within the "rows" object, each containing similar keys and values except for the "values" and "display" keys.

{
  "pages": [
    {
      "label": "SomeLabel",
      "name": "Some",
      "sections": [
        {
          "type": "Repeat",
          "label": "Label 1",
          "name": "Name 1",
          "rows": [
            {
              "pages": [
                {
                  "label": "Label 1",
                  "name": "Name 1",
                  "sections": [
                    {
                      "type": "Flow",
                      "label": "Label 2",
                      "name": "Name 2",
                      "answers": [
                        {
                          "label": "Question Label",
                          "question": "Question",
                          "values": [
                            "Value A"
                          ],
                          "valuesMetadata": [
                            {
                              "display": "Display A",
                              "row": {
                                "columns": []
                              }
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              ]
            },
            {
              "pages": [
                {
                  "label": "Label 1",
                  "name": "Name 1",
                  "sections": [
                    {
                      "type": "Flow",
                      "label": "Label 2",
                      "name": "Name 2",
                      "answers": [
                        {
                          "label": "Question Label",
                          "question": "Question",
                          "values": [
                            "Value B"
                          ],
                          "valuesMetadata": [
                            {
                              "display": "Display B",
                              "row": {
                                "columns": []
                              }
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ],
          "footer": null
        }
      ]
    }
  ]
}

The new JSON structure involves a single "pages" object within the "rows" object, with multiple values for the "values" and "display" keys.

{
  "pages": [
    {
      "label": "SomeLabel",
      "name": "Some",
      "sections": [
        {
          "type": "Repeat",
          "label": "Label 1",
          "name": "Name 1",
          "rows": [
            {
              "pages": [
                {
                  "label": "Label 1",
                  "name": "Name 1",
                  "sections": [
                    {
                      "type": "Flow",
                      "label": "Label 2",
                      "name": "Name 2",
                      "answers": [
                        {
                          "label": "Question Label",
                          "question": "Question",
                          "values": [
                            "Value A",
                            "Value B"
                          ],
                          "valuesMetadata": [
                            {
                              "display": [
                                "Display A",
                                "Display B"
                              ],
                              "row": {
                                "columns": []
                              }
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ],
          "footer": null
        }
      ]
    }
  ]
}

I am seeking a simple and efficient method to achieve this JSON restructuring. Your guidance on the process and techniques would be greatly appreciated.

Thank you

Answer №1

If my understanding is correct, you are looking to consolidate all pages into a single page that contains all the information.

This can be accomplished using the Array.reduce method. reduce takes an array and combines all elements into a single value using a function (provided by you) to merge the first two elements until only one is left (for example,

1 * 2 => new1; new1 * 3 => new2
where * represents the function you provide).

Your issue can be addressed with a solution like this:

rows[0].pages = rows[0].pages.reduce((currentElement, currentState) => {
    if (!currentState) { // for the initial iteration, return the first element but ensure display is an array
        currentElement.sections[0].answers[0].valuesMetadata[0].display =
            [currentElement.sections[0].answers[0].valuesMetadata[0].display];
        return currentElement;
    }

    // merge values of current element into arrays in current state
    currentState.sections[0].answers[0].values
        .concat(currentElement.sections[0].answers[0].values);
    currentState.sections[0].answers[0].valuesMetadata[0].display
        .concat(currentElement.sections[0].answers[0].valuesMetadata[0].display);
    return currentState;
});

currentElement is the object of the array being reduced at the moment, while currentState is the interim outcome of the reduction.

PS:

It seems like there are excessive arrays in your object where they may not be necessary. The provided code snippet only works for the first element in each array (hence the [0]s). If you do have multiple values in each array, you will need to iterate through them accordingly.

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

The process of extracting all arrays from a JSON object

Within my JSON object, there is a list of countries each with multiple regions stored in an array. My goal is to extract and combine all the regions into one single list. However, when I attempt to map the data, it does not consolidate all the regions as e ...

odd appearance when objects make contact with one another

I am encountering a peculiar issue with my threejs objects in a scene. Whenever they get near each other or touch, I notice strange triangular artifacts forming at the borders of the objects, as shown in the image below. The renderer being used is THREE.W ...

"Encountered an issue: Error occurred while attempting to synchronize Protractor with the page" during the execution of Protractor tests

I am facing an issue while running Protractor tests on a web application that includes both Angular and non-angular elements. Here is the structure of my code: describe("Test Name", function() { it("Test case", function() { // starting with steps on ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

Tips for avoiding cursor sticking in css rotate transform in firefox?

I have a unique challenge in this code where I want the user to grab the black square and rotate it around the inner circle. Check out the code snippet here. While attempting to rotate the square, you might notice that the cursor sometimes gets stuck in ...

Retrieve the initial occurrence that meets the conditions across three columns in MySQL

I am currently utilizing a NodeJS REST API that connects to a MySQL database. Within this database, there is a specific table we will refer to as Table_01: | C_0| C_1| C_2| C_3| | 1 | A1 | B1 | 1 | | 2 | A1 | B2 | 0 | | 3 | B1 | A1 | 0 | | 4 | A2 | ...

Attempting to perform a second HTTP GET request on a nodejs/express backend will result in an

Utilizing the express and ftp packages, I am attempting to fetch files from an FTP server and then display them to the client via HTTP GET requests. The initial request is successful, but upon trying to make another call, I encounter the following Excepti ...

Methods for sending data from Angular to the server and vice versa

Currently, I have an application that utilizes Express along with Jade templates. I am in the process of developing a new version of the app using Angular and client-side HTML. In order to determine user permissions within my Angular code, I require acces ...

Exploring methods for testing an HTML page that utilizes jQuery for DOM manipulations

Recently, I was tasked with creating an HTML page that utilized jQuery DOM manipulations. For instance, upon clicking the submit button, a success or error message should be displayed. Testing these functionalities is something I'm familiar with in An ...

Tips for adjusting the header color in materialize framework?

I've been working on a web template and I'm looking to customize the color displayed in the Android browser (maybe using JS?). The default color is blue. How can I go about changing it? https://i.sstatic.net/RxLbS.jpg Appreciate any help! ...

Having trouble accessing AJAX POST data in Python?

For this jQuery request, I utilize an HTTP POST. function retrieveData() { const information = JSON.stringify({ "test_id": "1" }); jQuery.post('/retrieveData', information, function (response) { a ...

Issues with JQuery .attr method not functioning as expected

I'm having trouble with the .attr() function in jQuery. It doesn't seem to be changing the background-color of the div with the id "outline" like I expected. Here's an example of my code: <div id="outline"></div> And here is t ...

Arranging a nested JSON array directly

Below is the structure of my JSON data : Root |- cells [] |-Individual cells with the following |- Facts (Object) |- Measures (Object) |- Key value pairs |- other valu ...

Steps to create an instance method that only accepts the name of another instance method

I am looking to enhance an object by adding a method that specifically accepts the name of another method within the object. How can I achieve this in a way that dynamically narrows down the accepted names of methods, without hardcoding them? Let's t ...

Is there an alternative solution to the issue of the jQuery resize() event not triggering when an input is

Despite the fact that the jQuery event resize() should trigger when the width of an input box changes, it seems to be malfunctioning. As per the jQuery API documentation, the resize event is supposed to go to the (window) handler. So my query here is, what ...

How come my strategies for React function components aren't producing results?

Currently, I am working on a project that involves utilizing the Moviedb API. In this project, I have developed a Movie component to display a list of movies and handle API requests. From the Movie component, I pass on the movie's release date and gen ...

Exploring the possibilities of using React for looping?

I have integrated Dexie.js with React for this specific example. However, the implementation details are not of great importance to me. My main focus is on finding out how to iterate through all objects in my IndexDB database using React. In the code snip ...

Show me a list of either only development or production dependencies in npm

When attempting to list only the production dependencies from package.json according to the npm docs, I tried: npm list -depth 0 -prod or npm list -depth 0 -only prod However, npm continues to list both dependencies and devDependencies. Can anyone sugg ...

What is the best way to integrate model classes within an Angular module?

I have a few classes that I want to keep as plain bean/DTO classes. They are not meant to be display @component classes, @Pipe classes, or @Directive classes (at least, that's what I believe!). I am trying to bundle them into a module so that they ca ...

Expanding URL path parameters in Angular's ui-routerWould you like to

Can UI-router handle this type of routing? Parent state - /saved/:id Child state - /saved/:id/eat Here is the code snippet I am using. However, when I attempt to access it, the page redirects: .state('fruits.banana.saved', { url: &apo ...