react-d3-tree icon indicating copy to clipboard operation
react-d3-tree copied to clipboard

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

Open paulano1 opened this issue 3 years ago • 0 comments

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;
}

'''

paulano1 avatar Dec 26 '22 19:12 paulano1