Advice on clearing down data on hiding a Group

I struggled with this issue for some time before finding a solution.
I remember finding a couple of threads here that spoke about this but i’ll leave my solution here and tag @sdirix for future references.

import {
  isControl,
  isVisible,
  JsonFormsCore,
  UISchemaElement,
} from '@jsonforms/core';
import { get, set } from 'lodash';

import { jsonFormAjv } from '../../../components/JsonForm/JsonForm';

interface ElementContainingElements extends UISchemaElement {
  elements: UISchemaElement[];
}

const hasElements = (
  uiElement: UISchemaElement,
): uiElement is ElementContainingElements => {
  return Object.hasOwn(uiElement, 'elements');
};

// a recursive function that check whether the uiElement of a json schema or any
// of it's parents is invisible and sets the data as undefined if so
export const removeInvisibleFormData = (
  uiElement: UISchemaElement,
  data: JsonFormsCore['data'],
  isParentVisible: boolean = true,
) => {
  const visible =
    isVisible(uiElement, data, '', jsonFormAjv) && isParentVisible;

  if (hasElements(uiElement)) {
    uiElement.elements.forEach((element) => {
      removeInvisibleFormData(element, data, visible);
    });
  }

  if (isControl(uiElement)) {
    const path = uiElement.scope
      .replaceAll('properties', '.')
      .split('/')
      .filter((el) => el.length > 1)
      .join('.');

    const elementData = get(data, path);
    if (!!elementData && !visible) {
      set(data, path, undefined);
    }
  }

  return data;
};

This will filter out the data that is not visible based on its scope.