Combining array objects in JavaScript using AJAX with identical keys

In my MVC 5 application, I am utilizing Ajax to create an array as shown below:

$.ajax({
            type: "Post",
            url: '@Url.Action("Getthereport", "Surveys")',
            async: false,
            cache: false,
            dataType: "json",
            data: { 'test': "All" },
            success: function (result) {

                if (result && result.Grid.length > 0) {
                    for (let i = 0; i < result.Grid.length; i++) {
                        jsonData.push({
                            Question: result.Grid[i].Body,
                            QuestionId: result.Grid[i].QuestionId,
                            myData: { name: result.Grid[i].name, value: result.Grid[i].value }
                          });
                    };
                }
               },
            complete: function () {
               reduce();
            },
            error: function(err) {
                alert(err.status + " : " + err.statusText);
            }
        });

The generated result is as follows:

var jsonData = [
            {
                Question: "Was the training useful?",
                QuestionId: 1,
                myData: [{ name: 'No', value: 1 }] },
            {
                Question: "Was the training useful?",
                QuestionId: 1 ,
                myData: [{ name: 'Yes', value: 1 }]
        }];

To merge these objects, I employ the following code:

const result = Object.values(jsonData.reduce((acc, obj) => {
  if (!acc[obj.QuestionId]) {
    acc[obj.QuestionId] = obj;
  } else {
    acc[obj.QuestionId].myData = acc[obj.QuestionId].myData.concat(obj.myData);
  }
  return acc;

This works perfectly when the array is hardcoded and results in:

var jsonData = [
        {
            Question: "Was the training useful?",
            QuestionId: 1,
            myData: [{ name: 'No', value: 1 },
                     { name: 'Yes', value: 1 }] 
          }]; 

However, when the array is generated via an Ajax call, I encounter the following error:

 acc[obj.QuestionId].myData.concat is not a function

I attempted running the reduce script on Ajax completion and directly, but neither approach worked.

Answer №1

Ensure to note that in the success attribute of your ajax request, you are appending myData as an object and not an array.

  success: function (result) {

    if (result && result.Grid.length > 0) {
      for (let i = 0; i < result.Grid.length; i++) {
        jsonData.push({
          Question: result.Grid[i].Body,
          QuestionId: result.Grid[i].QuestionId,
          myData: { name: result.Grid[i].name, value: result.Grid[i].value }
        });
      };
    }
  },

This indicates that the outcome deviates from what was initially specified, instead:

var jsonData = [
  {
    Question: "Was the training useful?",
    QuestionId: 1,
    myData: { name: 'No', value: 1 } //<-- Objects not arrays
  },
  {
    Question: "Was the training useful?",
    QuestionId: 1,
    myData: { name: 'Yes', value: 1 }
  }
];

To rectify this, you can either convert it to an array at that stage to produce the intended output,

      for (let i = 0; i < result.Grid.length; i++) {
        jsonData.push({
          ...
          myData: [{ name: result.Grid[i].name, value: result.Grid[i].value }]
        });
      };

or modify your reduction method accordingly.

var jsonData = [
  {
    Question: "Was the training useful?",
    QuestionId: 1,
    myData: { name: 'No', value: 1 }
  },
  {
    Question: "Was the training useful?",
    QuestionId: 1,
    myData: { name: 'Yes', value: 1 }
  }
];


const result = Object.values(jsonData.reduce((acc, obj) => {
  acc[obj.QuestionId] ??= { ...obj, myData: [] };
  acc[obj.QuestionId].myData.push(obj.myData);
  return acc;
}, {}));

console.log(JSON.stringify(result, null, 2))

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

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery. Specifically, I want to make changes to my CSS when a user is logged in. By default: body{ background: url('image.jpg ...

Pass a two-dimensional array as a one-dimensional array to a function in C

When passing a two-dimensional array as a one-dimensional array to a function in C, I understand the visible result but not what happens behind the scenes. By using function((char*)array) and receiving function(char *array), I create a pointer capable of h ...

What are the steps to adjust the size of the Facebook "like" button?

Is there a way to modify the size of the Facebook like button? I attempted to adjust the padding of <a class="connect_widget_like_button clearfix like_button_no_like"> using jQuery, but was unsuccessful. Any suggestions on how this can be achieved? ...

Automatically update the Vuex state with dynamic data

In the root component, I am looking to load a different version of state based on a specific 'data' variable. App.vue: export default { store: store, name: 'app', data() { clientId: 1 } } store.js: export const store = ...

How can I keep the cursor from automatically moving to the beginning of an input field when the type changes?

Currently in the process of creating a Password field that allows users to hide or display their password in React/Ionic. I am aiming to maintain focus on the password field when switching the input type, similar to how it is done on the PayPal Login page ...

What is the best way to obtain a direct file link from a server URL using JavaScript?

After acquiring a file located at /home/johndoe/index.html, I am utilizing a tool like XAMPP to host, with the folder /home being hosted on localhost. The variables in play are as follows: $server_addr = "localhost"; $server_root = "/home"; $file_dir = " ...

Prototype: Trigger keydown event on the document and cease observation when focus is on a form

I'm implementing next/previous page functionality with AJAX and left/right arrow keys (similar to Facebook). It's all working fine, but I have a form on the page. When a user focuses on the form, I need to stop listening for left/right key presse ...

Performing two simultaneous AJAX requests using tokeninput

I've been playing around with the tokeninput plugin and it's been working really well for me. However, I recently came across a new requirement - I need to make two separate ajax calls on the same input bar. Situation: My input bar is as follows ...

Retrieve data from a JavaScript function that specifies the country, state, city, and locality, providing a complete address in a Spring MVC application

I need to include country, state, city, and the remaining address if available. However, I am not well-versed in using Google API with JavaScript. Currently, I am utilizing a pre-existing JavaScript function that populates the full address in a textbox aft ...

Creating a four-dimensional array in PHP can be achieved by nesting multiple arrays within each

When I run a distinct query, I end up with a lot of data. Take a look at this picture of a busy cat: My goal is to group the final status by nodeid, portid, and total, which represents the total status. I need to create an array that looks like this: [ ...

Identify the credit card as either American Express or American Express Corporate

My JavaScript code can successfully detect credit card types, but I have encountered an issue. I am unable to differentiate between American Express and American Express Corporate cards. Is there a way to distinguish them or is it impossible to identify wh ...

enhancing the functionality of appended children by including a toggle class list

I'm having trouble toggling the classList on dynamically appended children. The toggle works fine on existing elements, but not on those added through user input. Any tips on how I can achieve this? I'm currently stumped and would appreciate any ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...

Creating a dynamic JSON object and retrieving the response in a JSP for data-driven documents

I am a beginner with the D3 API and I need to create a tree-like structure using a JSON file with hardcoded values. Additionally, I have a servlet that retrieves some values from a database which I want to dynamically convert into JSON in the servlet and s ...

Maintain cookie persistence beyond browser shutdown

Using this code snippet in Node-Express JS, I am creating a cookie with a JWT token included. Here is the code: var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"}); res.setHeader('Set-Cookie', 'token='+token+&apos ...

Creating a dropdown menu in React

Imagine having an options array like the one below: options = [ { name: 'My profile' }, { name: 'Sign out' } ] public selectOptions(showOptions: boolean) { this.setState({ showOptions: !showOptions }) return options.map((opt ...

The error message is stating that there is a TypeError because it cannot read the property "bind" of an undefined value when using the ng

When trying to implement the ng-cropper directive, an angular binding for the cropper javascript image cropping library, I'm encountering the error message TypeError: Cannot read property 'bind' of undefined. It seems to be related to the fo ...

What is the best method for passing page props in Next.JS?

One example is using the React Context API to pass props from the _app file to pages. Another scenario involves refactoring a ReactJS routing, where state is passed from app.js to pages through the route definition as shown below: <Route><Compon ...

What is the best way to deactivate select option(s) based on the JSON data retrieved through AJAX?

I am facing an issue with a dropdown menu that contains several options. My goal is to loop through these options and set the disabled attribute on specific ones based on the result of an Ajax call. https://i.sstatic.net/9k3f9.png This is what I am tryin ...