От сервера приходит ответ, вложенность дочерних элементов может любая. Нужно вывести список с вложенными элементами. Попробовал рекурсивно обработать ответ, но получаю ошибку "forEach is not a function"при вычислении вложенного массива.
код:
let response = [{
"isparent": true,
"name": "Тестовое 1",
"objectid": "fb27a8af-5675-40a7-a717-35f31743787b",
"child": [{
"isparent": true,
"name": "Тестовое 11",
"objectid": "fb27a8af-5675-40a7-a717-35f31743787b",
"child": [{
"isparent": false,
"name": "Тестовое 12",
"objectid": "fb27a8af-5675-40a7-a717-35f31743787b",
"child": []
}]
}]
},
{
"isparent": false,
"name": "Тестовое 6",
"objectid": "d00e93d6-5cdc-4c0a-a39d-bd86c9de9f13"
},
{
"isparent": false,
"name": "Тестовое 7",
"objectid": "4b2f28b2-dd5c-4075-a2fc-d3459ad4294e",
"child": []
},
{
"isparent": false,
"name": "Тестовое 14",
"objectid": "d237bc0f-ab13-4e3f-9cac-ca38f43e9ac7",
"child": []
},
{
"isparent": true,
"name": "Тестовое 15",
"objectid": "35e3e74d-912e-452a-a7af-dd54c82018b9",
"child": [{
"isparent": false,
"name": "Тестовое 89",
"objectid": "fb27a8af-5675-40a7-a717-35f31743787b",
"child": []
}]
}
]
function getStruct(data) {
let retstr = '';
data.forEach(function (item) {
let children = item.child
if(item.isparent){
retstr += '<li><span class="open-child">+</span><span class="caret" data-objectId="' + item.objectid + '">' + item.name + '</span><ul>'
children.forEach(value=>{
retstr += getStruct(value);
});
retstr += '</ul></li>';
} else {
retstr += '<li>'+item.name+'</li>';
}
});
return retstr;
}
let result = getStruct(response);
$('.result').html(result)