Here is an array that I have:
{
"id": "parent",
"code": "parent",
"children": [
{
"id": "rtsp",
"code": "rtsp",
"children": [
{
"id": "001",
"code": "cam30",
"source": "rtsp://192.168.43.29:8554/test",
"sourceFullScreen": "rtsp://192.168.43.29:8554/test"
},
{
"id": "002",
"code": "cam31",
"source": "rtsp://192.168.43.29:8554/test",
"sourceFullScreen": "rtsp://192.168.43.29:8554/test"
},
...
(more children elements here)
]
},
{... (other parent element)}
{... (more parent elements)}
]
}
I am looking to retrieve the codes of all elements that have children.
My attempt at it was as follows:
jsonfile.readFile(file)
.then(obj => {
json = JSON.parse(JSON.stringify(obj));
elements = getAllParents(json);
console.log(elements);
$('#parent').empty();
$('#parent').append(firstChoice);
$('#parent').append(elements);
})
.catch(error => console.error(error))
.
.
.
function getAllParents(json) {
let childP = "";
function read(json) {
console.log(json);
if (json.children !== undefined) {
for (let i = 0; i < json.children.length; i++) {
const element = json.children[i];
childP += read(element);
console.log(childP)
}
if(childP.includes(json.code) === false) childP += `<option value="` + json.code + `" >` + json.code + `</option>`;
}
return childP;
}
return read(json);
}
However, I am encountering an issue where my elements are being repeatedhttps://i.sstatic.net/DgArw.png
Can someone help me identify the error and suggest a resolution?