Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dependency free function to convert flat data to tree #12

Open
johannesmutter opened this issue Dec 6, 2022 · 0 comments
Open

Dependency free function to convert flat data to tree #12

johannesmutter opened this issue Dec 6, 2022 · 0 comments

Comments

@johannesmutter
Copy link

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,
          }
        }
      }
    }
  `;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant