I know there are a lot of similar questions here but they are different from mine. basically I have an Ajax call that return me an array of objects that are nested in more levels. the problem is that I don’t know neither how many the levels are nor the property names of them. so I made a recursive function for extracting the data from it and build a string that I’m going to append to the Dom after reading all the keys and values inside the object.
the json is an array with inside three objects that have inside of them arrays of objects sometimes.I wrote this code:
$.ajax({
type:'GET',
url:'/apiTlvArchive/tlvListAuditRecords',
data:{
xFilterObj:strObject
},
success:(result)=>{
if(result.AuditRecords){
AuditRecords=result.AuditRecords
Docreatefiltersessiontable(AuditRecords)
}
},error:(error)=>{
error.responseJSON.ErrorCode===9004 ? showErrorAlertMsg('Intervallo date seleionato troppo lungo') : showErrorAlertMsg('errore in list auditrecords')
}
})
}
in the success callback I then call a function that is going to configure the table(I use datatables plugin) and inside this function I call the recursive function for reading the Json and creating a string that is gonna be appended to the DOM. the code is as follows:
function Docreatefiltersessiontable(AuditRecords){//crea tabella in tab filtra sessione
let tablestring=''
tablestring+=`<thead>
<tr><th>Parametro</th><th>Valore</th></tr>
</thead><tbody>`
tablestring+= processObject(AuditRecords)
tablestring+='</tbody>'
document.getElementById('FiltersessionTable').innerHTML=tablestring
FiltersessionTableinstance= $("#FiltersessionTable").DataTable({
scrollY: 500,
scrollX: false,
scrollCollapse: false,
deferRender: true,
paging: true,
ordering: false,
searching: true,
info: false,
searchDelay: 350,
pageLength: 50,
columnDefs: [
{
"width": "15%",
"targets": 0
},
{
"width":"12%",
"targets":1
},
]
});
}
and finally the recurisve function:
function processObject(jsonObject) {
let strSource=''
for (var property in jsonObject) {
if (jsonObject.hasOwnProperty(property)) {
if (typeof (jsonObject[property]) == 'object') {
strSource+=processObject(jsonObject[property]);
// processObject(jsonObject[property]);
}
if(isNaN(property) && typeof(jsonObject[property])!=="object"){//voglio escludere indici e object di object
strSource+=`<tr>
<td>${property}</td>
<td>
${jsonObject[property]}
</td>
</tr>`
}
}
}
return strSource;
}
I get the stack exceedeed error only when I try to create the string inside of the function when the objects are a little more than usual. the fact is that the recursive function works fine for just reading the keys and values, but if i try to create something like the string, there’s always the point where is gonna cause the stack excedeed error.I need to do a recursive function cause I don’t know prior the keys of this Json. Any idea on how to fix this problem? is there another solution or recursion is the only one I have?