skip to Main Content

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 .

3

Answers


  1. You want to create a recursive function that searches for an item with a given boxId and removes it from the given JSON structure. Here’s how you can do it:

    • Check the root level of the JSON for any files or folders with the given boxId.
    • If a match is found at the root level, remove it and return.
    • If no match is found, then recursively check inside each folder’s files and subfolders.
    • If a match is found inside a folder, remove it and return.

    Here’s the code:

    def remove_node_by_id(data, boxId):
        # Check and remove from files at current level
        data['files'] = [file for file in data.get('files', []) if file['boxId'] != boxId]
        
        # Check folders
        for i, folder in enumerate(data.get('folders', [])):
            # If folder matches the boxId, remove it
            if folder['boxId'] == boxId:
                del data['folders'][i]
                return
            # Else, check recursively inside the folder
            remove_node_by_id(folder, boxId)
        
        # Clean up any empty folders after the removal
        data['folders'] = [folder for folder in data.get('folders', []) if folder['files'] or folder['folders']]
    

    To use the function:

    json_data = {
        # ... [your JSON structure here]
    }
    
    boxId_to_remove = "45325252435235"
    remove_node_by_id(json_data, boxId_to_remove)
    

    This function will modify the given json_data in-place to remove the item with the specified boxId.

    Login or Signup to reply.
  2. This should get you started –

    function removeId({ files = [], folders = [], ...node }, id){
      return node.boxId === id
        ? []
        : [{ ...node, files: files.flatMap(f => removeId(f, id)), folders: folders.flatMap(f => removeId(f, id)) }]
    }
    

    Run the demo to verify in your own browser –

    function removeId({ files = [], folders = [], ...node }, id){
      return node.boxId === id
        ? []
        : [{ ...node, files: files.flatMap(f => removeId(f, id)), folders: folders.flatMap(f => removeId(f, id)) }]
    }
    
    const node = {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: []}]}
    
    console.log(removeId(node, "34534534534535"))
    .as-console-wrapper { min-height: 100%; top: 0; }
    [
      {
        "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,
            "files": [],
            "folders": []
          },
          {
            "boxId": "43534534543534",
            "modifiedDate": null,
            "name": "Original Supporting docs.msg",
            "size": null,
            "files": [],
            "folders": []
          }
        ],
        "folders": []
      }
    ]
    
    Login or Signup to reply.
  3. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search