bkrem / react-d3-tree

:deciduous_tree: React component to create interactive D3 tree graphs
https://bkrem.github.io/react-d3-tree
MIT License
1.06k stars 268 forks source link

A helper function if anyone is trying to convert a regular nested json to the data format specified by the library #428

Open paulano1 opened 1 year ago

paulano1 commented 1 year ago

function convertToRawNodeDatum(json: Record<string, string | number | boolean>): RawNodeDatum[] {
  if (json === null || typeof json !== 'object') {
    throw new Error('Input must be a non-null object');
  }

  const rawNodeData: RawNodeDatum[] = [];

  for (const key in json) {
    const value = json[key];
    const rawNodeDatum: RawNodeDatum = { name: key };

    if (Array.isArray(value)) {
      rawNodeDatum.children = value.map(convertToRawNodeDatum).flat();
    } else if (typeof value === 'object') {
      rawNodeDatum.children = convertToRawNodeDatum(value);
    } else {
      rawNodeDatum.attributes = { value: value };
    }

    rawNodeData.push(rawNodeDatum);
  }

  return rawNodeData;
}

'''