Creating a dynamically generated JavaScript array using the JSON format

I am in need of creating an array of JSON data. Here is an example:

[
    {
        "DataCategoryGroupId": "22222222-2222-2222-2222-222222222222",
        "AnswerOptionIds": [
            "76e32546-0e26-4037-b253-823b21f6eefb",
            "10d02a3e-9f9f-49fd-8806-e0b180465b7d"
        ]
    },
    {
        "DataCategoryGroupId": "33333333-3333-3333-3333-333333333333",
        "AnswerOptionIds": [
            "ee795c1b-71d1-476a-84f7-0d8084e25617",
            "b611309e-ccfc-44c4-a0e1-60f0767d20ba",
            "7066eb9a-6d08-4f34-8348-b10523e8a568"
        ]
    }
]

My approach to building this array is as follows:

var postParams = [];
            for (var i = 0; i < dataCategories.length; i++) {
                var postElement = {
                    DataCategoryGroupId: dataCategories[i].DataCategoryId,
                    AnswerOptionIds: dataCategories[i].AnswerOptionIds
                };
                postParams.push(postElement);
            }

To give you a glimpse into the content of dataCategories, here is some debug code:

for (var i = 0; i < dataCategories.length; i++) {
                console.log("Data Category Id: " + dataCategories[i].DataCategoryId);
                console.log("Answer Option Ids: " + dataCategories[i].AnswerOptionIds);
            }

The output generated by the above code snippet is:

Data Category Id: 22222222-2222-2222-2222-222222222222
Answer Option Ids: bf835029-5e3b-40d5-8736-34fe5121c5f4,10d02a3e-9f9f-49fd-8806-e0b180465b7d
Data Category Id: 33333333-3333-3333-3333-333333333333
Answer Option Ids: ee795c1b-71d1-476a-84f7-0d8084e25617,b611309e-ccfc-44c4-a0e1-60f0767d20ba,0049e914-520d-4721-92d2-9b0a050d7381

Although the data seems to be correct, I am encountering issues with constructing the JSON that do not align with the controller's expectations. However, when testing with a rest client using the provided JSON structure, everything works seamlessly.

I would appreciate any insights on where I might be going wrong in generating my JSON data.

Answer №1

In order to avoid potential issues, consider implementing a deep copy of the input array instead of just copying a reference. By doing so, you can ensure that any changes made to the original data will not affect the post data.

let postData = [];

for (let x = 0; x < categoriesData.length; x++) {
    const categoryElement = categoriesData[x];

    let postDataElement = {
        CategoryId: categoryElement.DataCategoryId,
        OptionIds: []
    };

    for (let y = 0; y < categoryElement.OptionIds.length; y++){
       postDataElement.OptionIds.push(categoryElement.OptionIds[y]);
    }
    postData.push(postDataElement);
}

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

When attempting to import the OrbitControls.js file, Three.js encounters an error and fails

I am completely new to javascript and unfamiliar with working with libraries. I am currently experimenting with basic three.js code, but unfortunately facing issues that I cannot seem to resolve. Following the documentation on Threejs.org, I have set up a ...

Pass JSON data to an ASP.net web method and convert it into an object through deserialization

I am facing an issue with an .aspx page where UserControls are dynamically loaded at runtime, each containing various controls such as textboxes or combo boxes. While everything functions correctly, I am unable to directly read the values from these contro ...

Testing units with Jest using ES6 import syntax instead of module.exports

There's a script I created that contains all the logic in a single const variable, similar to Moment.js. I'd like to test the functions from this script using Jest. Unfortunately, using module.exports won't work when I publish the script. ...

I would like to deserialize a JSON object to retrieve a String that represents

Dart programming language is truly remarkable. However, I have encountered a potential issue with the JSON.parse function in Dart that seems to be creating integers in the Map object when the input is actually a string. This could lead to unwanted outcomes ...

Issue with FullCalendar-v4 not displaying all-day events

I am facing an issue with my calendar where recurring events are displaying correctly, but single allDay events are not rendering, and I suspect it may be a field problem. I've attempted to set the event's start time as an iso date, but it doesn ...

What is the process for utilizing the tweed_mode= extended parameter in a Twitter REST API request?

I am in the process of developing a PHP application and sending the following request: $data= $mycon->get("/statuses/show/".$id); The above request functions correctly for tweets that are up to 140 characters and return extended entities if there are ...

Ways to discover the titles of every sub-directory

Suppose I have the absolute path of a directory. Is there a method in JavaScript (Node.js) to determine how many sub-directories it has, and retrieve the names of all its sub-directories? I searched online but didn't come across any solution. ...

What could be the reason behind the ajax call not getting triggered?

Upon page load, the first alert is displaying correctly. However, the alert inside the ajax call is not triggering. It appears that the ajax call itself is not functioning as intended - it is supposed to invoke a method in the controller, but no longer s ...

Is it possible to switch the summernote editor between airmode and toolbar mode?

Currently, I am working on creating a report editor that displays only one toolbar when multiple summernote WYSIWYG editor sections are used. My solution involves having the first section as a full editor and the other section in airmode. Below is the HTM ...

Aligning images with absolute CSS to text that is wrapping positions the images perfectly alongside the text content

My webpage has a long content section that resizes based on the browser width. Here's an example: <h1 id="loc1">Title</h1> <p>bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bod ...

Struggling with JSON parsing on iPhone? json-framework can help!

Currently, I am utilizing the json-framework and require assistance in parsing some JSON data received from my server. The structure of the JSON data is as follows: I have already installed the json-framework but I am struggling to parse it correctly. Ca ...

Turn off Chrome 69's autofill functionality

I've recently encountered an issue with Chrome's password autofill feature that has been troubling me for a few days now. This problem began when I was using Chrome version 69. After much trial and error, I found a solution by removing the id an ...

Dynamic count down using JavaScript or jQuery

I am looking for a way to create a countdown timer that I can adjust the time interval for in my database. Basically, I have a timestamp in my database table that might change, and I want to check it every 30 seconds and update my countdown accordingly. H ...

What is the best way to display a child element in the right panel?

Hello, I need help in displaying child elements next to the parent element. My function works fine the first time, but fails the second time. Here are the steps I followed: 1) Clicked the Add button 2 times, generating row2 as well as a submenu of firs ...

How to hide an item in Ionic 2 using navparams

Is there a way to dynamically hide or show a list item on page load depending on certain parameters? Here is an example of the code I am currently using: HTML <button ion-item (tap)="goToPage2()" [hidden]="shouldHide">Page 2</button> TS ex ...

When attempting to access API>19 on my Android device, I encountered an error in my Interface to Java that stated: "TypeError: Android.method is not a function."

Having my minimum API set to 16, everything seems to be working fine. However, debugging has become quite a challenge. I've read that after API 19, the Chrome debugger can be used. But when it comes to interfacing with Java code, I encounter the error ...

Issues with JQuery .on() occur when functions are passed as arguments

There seems to be a difference in how the .on() function behaves when passing functions as parameters. Interestingly, defining the function inside the parameters versus passing it separately can have different results. An example of this discrepancy is de ...

When working with React-Native App and combining React-Navigation with Redux, a common error may occur stating that 'action.routeName' is not an object. This issue can be

I encountered an error in my React Native app while implementing react-navigation within redux. The issue, along with a screenshot for reference, can be found here. Currently, I have not incorporated any redirects into the application. However, my plan in ...

Tips for adding text dynamically to images on a carousel

The carousel I am using is Elastislide which can be found at http://tympanus.net/Development/Elastislide/index.html. Currently, it displays results inside the carousel after a search, but I am struggling to dynamically add text in order to clarify to use ...

Having trouble with importing a variable in an Express application? You may encounter this error message: "Route.get() must

When trying to import requireSignin from the controllers/auth.js file into the routes/user.js file and adding it to the router.get('/user/:id', requireSignin, read); route, an error occurs: Error: Route.get() requires a callback function but r ...