Вы можете иметь одну рекурсивную функцию, которая отслеживает текущий уровень отступа в качестве параметра. Когда его необходимо вызвать рекурсивно, объедините ' '
с параметром:
function append(parent, indent = '') {
for (const item of parent) {
createElement(item, indent);
if (item.Children) {
append(item.Children, indent + ' ');
}
}
}
append(recursiveArray); // initial call
Текущий фрагмент:
var recursiveArray = [{
"ProductCode": "50007",
"SerialNumber": 288890,
"SubAssemblyNumber": 288891,
"Children": [{
"ProductCode": "50007",
"SerialNumber": 288891,
"SubAssemblyNumber": 288892,
"Children": [{
"ProductCode": "51660",
"SerialNumber": 288892,
"SubAssemblyNumber": 288894
}]
}, {
"ProductCode": "51660",
"SerialNumber": 288891,
"SubAssemblyNumber": 288893
}]
}, {
"ProductCode": "51660",
"SerialNumber": 288890,
"SubAssemblyNumber": 288895,
"Children": [{
"ProductCode": "50007",
"SerialNumber": 288895,
"SubAssemblyNumber": 288896
}]
}];
if (recursiveArray.length > 0) {
$('#AttachedSubAssembly').append(`
<tr>
<th width="60%">Subassy S/N</th>
<th width="20%">Product code</th>
<th width="10%">Stock</th>
<th width="10%">Destroy</th>
</tr>
`);
}
function append(parent, indent = '') {
for (const item of parent) {
createElement(item, indent);
if (item.Children) {
append(item.Children, indent + ' ');
}
}
}
function createElement(item, indent) {
$('#AttachedSubAssembly').append(`
<tr id="Row${item.SubAssemblyNumber}">
<td> ${indent} <a class="btn-green bg-transparent" href="serial_number.html?serial_number=${item.SubAssemblyNumber}">
${item.SubAssemblyNumber}</a></td>
<td>${item.ProductCode}</td>
<td>
<div class="col-md-1">
<div class="radio radio-success">
<input type="radio" name="Options${item.SubAssemblyNumber}" id="Stock${item.SubAssemblyNumber}" value="Stock">
<label for="Stock${item.SubAssemblyNumber}" class="main-label"></label>
</div>
</div>
</td>
<td>
<div class="col-md-1">
<div class="radio radio-success">
<input type="radio" name="Options${item.SubAssemblyNumber}" id="Destroy${item.SubAssemblyNumber}" value="Destroy" checked="checked">
<label for="Destroy${item.SubAssemblyNumber}" class="main-label"></label>
</div>
</div>
</td>
</tr>
`);
}
append(recursiveArray);
table tr td {
border-style: solid;
border-width: 1px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="AttachedSubAssembly" class="table">
</table>