I have the following json setup which imitates a folder structure:
{
"boxId": "45345344535",
"modifiedDate": "2023-08-18T11:07:43-04:00",
"name": "FolderTest",
"size": 7751630,
"files": [
{
"boxId": "2343214243",
"modifiedDate": null,
"name": "Original Preprint Submission.pdf",
"size": null
},
{
"boxId": "43534534543534",
"modifiedDate": null,
"name": "Original Supporting docs.msg",
"size": null
}
],
"folders": [
{
"boxId": "34534534534535",
"modifiedDate": "2023-08-18T11:07:02-04:00",
"name": "Round 1",
"size": 4092614,
"files": [
{
"boxId": "45325252435235",
"modifiedDate": null,
"name": "Round 1 Preprint.pdf",
"size": null
},
{
"boxId": "45436567546754",
"modifiedDate": null,
"name": "Round 1 response.pdf",
"size": null
},
{
"boxId": "324243245435345",
"modifiedDate": null,
"name": "Round 1 supporting doc 1.pdf",
"size": null
},
{
"boxId": "3421342142142134",
"modifiedDate": null,
"name": "Round 1 supporting doc 2.docx",
"size": null
}
],
"folders": []
}
]
}
So I am trying to create a recursive function that takes the id and also the original array then finds the match then removes that file node. I found a similar post here:
Recursively remove object from nested array
But I am struggling to adapt it to my json structure .
>Solution :
Remove IN-PLACE:
const removeNode = (parent, id) => {
let idx = parent.files.findIndex(({boxId}) => id === boxId);
if(idx >= 0){
parent.files.splice(idx, 1);
return true;
}
for(let i = 0; i < parent.folders.length; i++){
if(parent.folders[i].boxId === id){
parent.folders.splice(i, 1);
return true;
}
if(removeNode(parent.folders[i], id)){
return true;
}
}
return false;
};
console.log('removing 3421342142142134:', removeNode(root, '3421342142142134'));
console.log(root);
<script>
const root = {
"boxId": "45345344535",
"modifiedDate": "2023-08-18T11:07:43-04:00",
"name": "FolderTest",
"size": 7751630,
"files": [
{
"boxId": "2343214243",
"modifiedDate": null,
"name": "Original Preprint Submission.pdf",
"size": null
},
{
"boxId": "43534534543534",
"modifiedDate": null,
"name": "Original Supporting docs.msg",
"size": null
}
],
"folders": [
{
"boxId": "34534534534535",
"modifiedDate": "2023-08-18T11:07:02-04:00",
"name": "Round 1",
"size": 4092614,
"files": [
{
"boxId": "45325252435235",
"modifiedDate": null,
"name": "Round 1 Preprint.pdf",
"size": null
},
{
"boxId": "45436567546754",
"modifiedDate": null,
"name": "Round 1 response.pdf",
"size": null
},
{
"boxId": "324243245435345",
"modifiedDate": null,
"name": "Round 1 supporting doc 1.pdf",
"size": null
},
{
"boxId": "3421342142142134",
"modifiedDate": null,
"name": "Round 1 supporting doc 2.docx",
"size": null
}
],
"folders": []
}
]
}
</script>