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.