2

I have flat file data in the following format:

d1       | d2           | d3       | d4
-------------------------------------------
Heading  |              |          |
         | Subheading   |          |
         |              | Entry1   |
         |              | Entry2   |
         | Another sub  |          |
         |              | Entry3   |
         |              | Entry4   |
         |              |          | Subentry

I can read the flat dsv just fine, and would like to stratify that, if at all possible. I was wondering if I can, inside of .parentId(), access previous rows and check if that is the parent.

Or do I write my own tree function?

Manuela Hutter
  • 823
  • 9
  • 16
  • You can make a hash table, e.g. make a map where key is id and value is row and then in second cycle get parent, if needed. – Vayrex Mar 25 '18 at 17:49
  • how is your dsv file ? Can you try to convert it to a valid json? Take a look at here,this may help: https://stackoverflow.com/questions/27979002/convert-csv-data-into-json-format-using-javascript – scraaappy Mar 26 '18 at 09:17
  • I do have valid (flat) json input, yes. I now managed to make it hierarchical by hand, see answer below. – Manuela Hutter Mar 26 '18 at 14:43

1 Answers1

2

So I made it work by writing my own tree, like so:

function tree(nodes) {
  var curr, parent, root;
  var lev = 1;

  nodes.forEach(function(d) {
    if (!root) {
      // handle root (first node)
      curr = {
        name:     d.d1,
        size:     1, //stub
        children: []
      };
      root   = curr;
      parent = curr;

    } else {

      if (d['d' + (lev+1)]) {
        // handle children
        lev = lev+1;
        parent = curr;

      } else if (d['d' + (lev-1)]) {
        // handle moving up the hierarchy
        lev = lev-1;
        parent = parent.parent;

      } else if (!d['d' + lev]) {
        // if it's neither child, nor moving up, nor a sibling, handle exception
        throw "unhandled tree level";
      }

      curr = {
        name:     d['d' + lev],
        size:     1, //stub
        children: []
      };
      curr.parent = parent;
      parent.children.push(curr);
    }
  });

  return root;
}
Manuela Hutter
  • 823
  • 9
  • 16