hierarchical-document-list icon indicating copy to clipboard operation
hierarchical-document-list copied to clipboard

Dependency free function to convert flat data to tree

Open johannesmutter opened this issue 2 years ago • 0 comments

Hi everyone,

In my frontend (using Svelte) I needed to convert the flat list of documents into a nested tree, without using react module as stated in the readme:

import {flatDataToTree} from '@sanity/hierarchical-document-list'

So instead of above’s module with several dependencies, here’s the standalone function:

const flatDataToTree = (data) => {

  // assign new ID "root" to parent for docs where parent == null (root level)
  data = data.map(doc => {
    if(doc.parent === null){
      return {
        ...doc, parent: 'root', children: []
      }
    }
    return {
      ...doc, children: []
    }
  });

  // create new root object
  let root = {_key: 'root', parent: null, children: []};
  let docList = { 'root' : root};

  // build tree
  for (var i = 0; i < data.length; i++) {
    docList[data[i]._key] = data[i];
    docList[data[i].parent].children.push(docList[data[i]._key]);
  }

  return root;
}

It needs the _key and parent fields to be present in data from your GROQ query:

  const query = `//groq
    *[_id == "YOUR-TREE-DOCUMENT-ID"][0]{
      tree[] {
        _key,
        parent,
        value {
          reference->{
            title,
            slug,
          }
        }
      }
    }
  `;

johannesmutter avatar Dec 06 '22 00:12 johannesmutter