What is the best way to move nested content to the parent level in a JavaScript array?

Within each subQuestion object, I have an array of questions that I need to extract and add to the parent level array, which is the subQuestion. The current code doesn't seem to be achieving this. Is there anything wrong with the following code snippet?

main.ts

if (_.isArray(_answerOption.subQuestion)) {
    for (let iLoop = 0, ll = _answerOption.subQuestion.length; iLoop < ll; iLoop++) {
        // Replace subQuestions entirely with the content of the question
        if (_answerOption.subQuestion && _answerOption.subQuestion[iLoop].question) {
            _answerOption.subQuestion = _.cloneDeep(_answerOption.subQuestion[iLoop].question);
        }
    }
}

data

{
    "nonClinicalIndicator": "Y",
    "questionId": 2558,
    "questionId2": 116523,
    "questionText": "How much of your medication(s) do you have left? For insurance purposes you must provide exact number of pills, injections, doses etc",
    "answerId": 0,
    "answerType": "SINGLE_SELECT",
    "responseFieldIdentifier": "DOSE LEFT IND",
    "answerOption": [
        {
            "answerOptionId": 2559,
            "answerOptionId2": 116524,
            "answerText": "Yes",
            "subQuestion": [
                {
                    "question": [
                        {
                            "nonClinicalIndicator": "Y",
                            "questionId": 2560,
                            "questionId2": 116525,
                            "questionText": "Number of doses left",
                            "answerId": 0,
                            "answerType": "TEXT",
                            "responseFieldIdentifier": "DOSE LEFT"
                        },
                        {
                            "nonClinicalIndicator": "Y",
                            "questionId": 2561,
                            "questionId2": 116526,
                            "questionText": "When will you take your next dose?",
                            "answerId": 0,
                            "answerType": "TEXT_DATE",
                            "responseFieldIdentifier": "NEXT DOSE"
                        }
                    ],
                    "rxNumber": "15127724",
                    "drugName": "TIKOSYN 250MCG CAPS",
                    "drugNdc": "00069581060"
                },
                {
                    "question": [
                        {
                            "nonClinicalIndicator": "Y",
                            "questionId": 2560,
                            "questionId2": 116525,
                            "questionText": "Number of doses left",
                            "answerId": 0,
                            "answerType": "TEXT",
                            "responseFieldIdentifier": "DOSE LEFT"
                        },
                        {
                            "nonClinicalIndicator": "Y",
                            "questionId": 2561,
                            "questionId2": 116526,
                            "questionText": "When will you take your next dose?",
                            "answerId": 0,
                            "answerType": "TEXT_DATE",
                            "responseFieldIdentifier": "NEXT DOSE"
                        }
                    ],
                    "rxNumber": "15127730",
                    "drugName": "TACROLIMUS 1MG CAPS",
                    "drugNdc": "55111052601"
                }
            ]
        },
        {
            "answerOptionId": 2562,
            "answerOptionId2": 116527,
            "answerText": "No"
        }
    ]
}

Expected Output

{
    "nonClinicalIndicator": "Y",
    "questionId": 2558,
    "questionId2": 116523,
    "questionText": "How much of your medication(s) do you have left? For insurance purposes you must provide exact number of pills, injections, doses etc",
    "answerId": 0,
    "answerType": "SINGLE_SELECT",
    "responseFieldIdentifier": "DOSE LEFT IND",
    "answerOption": [
        {
            "answerOptionId": 2559,
            "answerOptionId2": 116524,
            "answerText": "Yes",
            "subQuestion": [
                {
                    "nonClinicalIndicator": "Y",
                    "questionId": 2560,
                    "questionId2": 116525,
                    "questionText": "Number of doses left",
                    "answerId": 0,
                    "answerType": "TEXT",
                    "responseFieldIdentifier": "DOSE LEFT",
                    "answerOption": [
                        {
                            "answerOptionId": 0,
                            "answerText": "DRUG 1one dose",
                            "answerOptionId2": 0
                        }
                    ]
                },
                {
                    "nonClinicalIndicator": "Y",
                    "questionId": 2561,
                    "questionId2": 116526,
                    "questionText": "When will you take your next dose?",
                    "answerId": 0,
                    "answerType": "TEXT_DATE",
                    "responseFieldIdentifier": "NEXT DOSE",
                    "answerOption": [
                        {
                            "answerOptionId": 0,
                            "answerText": "2019-03-28",
                            "answerOptionId2": 0
                        }
                    ]
                },
                {
                    "nonClinicalIndicator": "Y",
                    "questionId": 2560,
                    "questionId2": 116525,
                    "questionText": "Number of doses left",
                    "answerId": 0,
                    "answerType": "TEXT",
                    "responseFieldIdentifier": "DOSE LEFT",
                    "answerOption": [
                        {
                            "answerOptionId": 0,
                            "answerText": "DRUG 2 one dose",
                            "answerOptionId2": 0
                        }
                    ]
                },
                {
                    "nonClinicalIndicator": "Y",
                    "questionId": 2561,
                    "questionId2": 116526,
                    "questionText": "When will you take your next dose?",
                    "answerId": 0,
                    "answerType": "TEXT_DATE",
                    "responseFieldIdentifier": "NEXT DOSE",
                    "answerOption": [
                        {
                            "answerOptionId": 0,
                            "answerText": "2019-03-31",
                            "answerOptionId2": 0
                        }
                    ]
                }
            ]
        },
        {
            "answerOptionId": 2562,
            "answerOptionId2": 116527,
            "answerText": "No"
        }
    ]
}

Answer №1

Here is a suggestion you can try:

const data = {
    "nonClinicalIndicator": "Y",
    "questionId": 2558,
    "questionId2": 116523,
    "questionText": "How much of your medication(s) do you have left? For insurance purposes you must provide exact number of pills, injections, doses etc",
    "answerId": 0,
    "answerType": "SINGLE_SELECT",
    "responseFieldIdentifier": "DOSE LEFT IND",
    "answerOption": [
        {
            "answerOptionId": 2559,
            "answerOptionId2": 116524,
            "answerText": "Yes",
            "subQuestion": [
                {
                    "question": [
                        {
                            "nonClinicalIndicator": "Y",
                            "questionId": 2560,
                            "questionId2": 116525,
                            "questionText": "Number of doses left",
                            "answerId": 0,
                            "answerType": "TEXT",
                            "responseFieldIdentifier": "DOSE LEFT"
                        },
                        {
                            "nonClinicalIndicator": "Y",
                            "questionId": 2561,
                            "questionId2": 116526,
                            "questionText": "When will you take your next dose?",
                            "answerId": 0,
                            "answerType": "TEXT_DATE",
                            "responseFieldIdentifier": "NEXT DOSE"
                        }
                    ],
                    "rxNumber": "15127724",
                    "drugName": "TIKOSYN 250MCG CAPS",
                    "drugNdc": "00069581060"
                },
                {
                    "question": [
                        {
                            "nonClinicalIndicator": "Y",
                            "questionId": 2560,
                            "questionId2": 116525,
                            "questionText": "Number of doses left",
                            "answerId": 0,
                            "answerType": "TEXT",
                            "responseFieldIdentifier": "DOSE LEFT"
                        },
                        {
                            "nonClinicalIndicator": "Y",
                            "questionId": 2561,
                            "questionId2": 116526,
                            "questionText": "When will you take your next dose?",
                            "answerId": 0,
                            "answerType": "TEXT_DATE",
                            "responseFieldIdentifier": "NEXT DOSE"
                        }
                    ],
                    "rxNumber": "15127730",
                    "drugName": "TACROLIMUS 1MG CAPS",
                    "drugNdc": "55111052601"
                }
            ]
        },
        {
            "answerOptionId": 2562,
            "answerOptionId2": 116527,
            "answerText": "No"
        }
    ]
};

// Start by destructuring the answerOption property since we will be working on it
const { answerOption, ...rest} = data;

const newAnswerOptions = [];

for (let i = 0; i < answerOption.length; i++) {

// Check if the answerOption property contains a subQuestion key that is not undefined
if (answerOption[i].subQuestion) {
const { subQuestion, ...restAnswers } = answerOption[i];
let questions = subQuestion.map(x => x.question).flat();
newAnswerOptions.push(Object.assign({}, restAnswers, { subQuestion: questions }));
}

// Otherwise, simply add it to the new array
else {
newAnswerOptions.push(answerOption[i]);
}
}

const res = { ...rest, answerOption: newAnswerOptions };

console.log(JSON.stringify(res, null, 4));

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

Taking an input value and transforming it into a percentage value to be utilized in a visual representation using a plotly pie chart

I am currently developing a budget calculator and I have a plan to convert user inputs into a pie chart. Once I figure out how to do this successfully, I can extend the same method to create charts for other sections as well. For testing purposes, let&apo ...

Is it possible to receive live updates from a MySQL database on a webpage using node.js and socket.io?

I've been following a tutorial that teaches how to receive real-time updates from a MySQL database using Node.js and Socket.io. Check it out here: Everything seems to work fine on the webpage. I can see updates in real-time when I open the page on tw ...

Mobile browser unable to show FB App

I created a fan-gate app for my page and it is working flawlessly on web browsers and my iPad browser. However, when I try to access it on my android mobile browser, I receive an error message saying "this page cannot be displayed." What could be causing ...

Trouble seeing span in ion-item in Ionic 2: How can I display plain text instead?

It seems like I may be overlooking something, as I am experiencing an issue with adding a span to an Ion Item, where the span is not being rendered, nor is the div. <ion-card> <ion-card-title> </ion-card-title> <div> < ...

Converting a JS string into HTML markup

I recently developed a basic web application to manage telnet connections with routers using Node.js, Express, and WebSockets. After establishing a connection, the terminal stream is transmitted through a websocket as UTF-8 strings. However, my current is ...

Obtaining the string representation of an HTML element's DOM in JavaScript without including its child elements

Is there a way to retrieve the HTML element/node without its children as a string? Even though this question may appear similar to another on Stack Overflow: jQuery, get html of a whole element, I'm specifically looking for just the HTML element i ...

The anchor link is not aligning properly due to the fluctuating page width

Seeking help to resolve an issue I'm facing. Maybe someone out there has a solution? The layout consists of a content area on the left (default width=70%) and a menu area on the right (default width=30%). When scrolling down, the content area expand ...

Creating MySQL queries programmatically using data stored in a JSON object

Is it possible to construct a MySQL query dynamically from a JSON object with potentially empty values? For instance, starting with an object like this: { "a": 1 "b": "" "c": "foo" } we want to generate a query like the following (ignoring the emp ...

Attempting to construct a webpage with the ability to create visual content

I've been struggling to kick off this project because I'm uncertain about what exactly I should be looking into. I would really appreciate any guidance on where or how to start. The concept is to enable users to upload an image of a postcard, in ...

Can someone guide me on the process of opening and closing a Material-UI Dialog within a Meteor/React application?

I'm attempting to create a dialog with a form that pops up when the user clicks a button. I followed the example on the Material-UI Dialog site for creating a button to open the dialog and adding a TextField within it. This is being done using Meteor ...

Create a variety of unique objects on the canvas without any repetition or unwanted overlapping

Is there a way to generate objects on a map in a HTML5 Canvas without them overlapping or occupying the same space? I tried checking inside an array to see if the next 20 values are already taken to prevent overlapping, but it didn't work as expected ...

In the realm of ASP.NET, the Razor FormExtensions.BeginForm Method holds the

In my current view, there is a dropdown list that allows the user to select an option which will then redirect them to another page or controller. I am using JavaScript to retrieve the selected value from the dropdown list, but I am facing difficulties whe ...

Issue encountered: An unexpected token = error appeared after updating from RN version 0.64.2 to 0.65.1

After upgrading from version 64.1 to 65.1 using the upgrade helper, I encountered an error that has been difficult to resolve. Even after updating node/npm to version 14.17 and trying various other solutions, I have not been able to fix this issue during ...

Internet Explorer is failing to show the results of an ajax call retrieved from the

Need help with this code block: $(document).ready(function() { dataToLoad = 'showresults=true'; $.ajax({ type: 'post', url: 'submit.php', da ...

Implementing NgRx state management to track and synchronize array updates

If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync? For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, ...

Issue encountered: The function car.reviews.find() is not recognized

Encountering an issue with the find() method in my MERN stack application. I am looking to implement a reviews route where users can add comments about cars within the app. In the frontend, fields and buttons have been added; meanwhile, a post request has ...

JavaScript 2 add or remove a class to the keyboard when opening or closing

As I work on developing an app in Ionic 2, I am facing a challenge where the background image needs to change when the keyboard is opened and closed in an input field. <ion-content padding class="bg_gogreen"> <ion-list> <ion-item class=" ...

Attempted to fetch information using Ajax in Grails

I am attempting to utilize jQuery and ajax with the Grails framework to load the content registration page. However, upon loading the page, I am encountering an issue where the menu and registration fields are duplicated within the page. <script src ...

Retrieve the size and position of the Kendo UI Splitter using the methods getSize()

I am currently working on a webpage using Kendo UI that allows users to customize the layout. I would like to implement a feature where the layout is saved so that the server can later send the user their last saved layout. One of the components I am usin ...

Vue.js - Displaying validation errors when a user interacts outside of a component

The ExamEditor Vue component I am working on is quite complex, consisting of sub-components like QuestionEditor and ExerciseEditor. These components are all tied to an exam object that contains nested arrays with questions and more. The layout inside the e ...