My application is MVC 5, I am using the following Ajax to generate an array:
$.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);
}
});
I generates the following:
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 the objects, I use:
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;
Works great if the array is hardcoded and generates:
var jsonData = [
{
Question: "Was the training useful?",
QuestionId: 1,
myData: [{ name: 'No', value: 1 },
{ name: 'Yes', value: 1 }]
}];
However, if the array is generated by Ajax call, I get the following error:
acc[obj.QuestionId].myData.concat is not a function
I tried to run the reduce script on Ajax complete and directly both did not work.
acc? Can you addconsole.log(acc)andconsole.log(typeof acc)?!acc[obj.QuestionId]returnstrueand in the other case it returnsfalse. Theelseblock causes the error. How is "console.log(acc) is not defined" possible?. Where do you run the code? I assume in a modern browser? Please provide a minimal reproducible example.jsonDatadoesn't contain JSON data, but a response contains JSON data. What is the difference between JSON and Object Literal Notation? This is confusing for many people.myData.concatat all the data has to be valid, it could be just another type than Array? (if it's any type that doesn't implement aconcatmethod it throws that error. ie. boolean, number, object )myDataas an object in yourajaxcalljsonData.push({Question: result.Grid[i].Body, QuestionId: result.Grid[i].QuestionId, myData: { name: result.Grid[i].name, value: result.Grid[i].value }})either wrap it in an array, or change your reduce to handle it as an object.