Skip to content
Advertisement

Create tree from 2D array and update Google Sheet

I’m trying to create a tree view (and dump that into a Google sheet) of our OrgUnits. I have the following script which pulls and sorts the data:

JavaScript

The above code produces the array called ouArray, which looks like this:

JavaScript

Now what I want to do is take that data, and format it and place it into a Google Sheet so that it resembles this:

JavaScript

If anyone has any idea’s on how I can accomplish this, it would be amazing. Logically (at least in my mind), it would need some kind of string/partial string match? But I can’t for the life of me figure it out!

Advertisement

Answer

Explanation:

The logic of the following script is quite simple:

  • Iterate through ouArray and forEach element find the number of forward slashes /.

  • Use a nested ternary operator and for each of the possible cases push the corresponding array to the final data array.

In more detail:*

  • 1 x /: append [t,"",""],
  • 2 x /: append ["",t,""],
  • 3 x /: append ["","",t]

where t is every element in ouArray.

*(1x/ means one forward slash etc.)

Complete Solution:

JavaScript

Reproducible example:

JavaScript

Output of reproducible example:

example

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement