transform file/directory structure into 'tree' in javascript

Posted by dave on Stack Overflow See other posts from Stack Overflow or by dave
Published on 2013-10-23T01:58:03Z Indexed on 2013/10/23 3:53 UTC
Read the original article Hit count: 138

Filed under:
|
|

I have an array of objects that looks like this:

[{ name: 'test',
  size: 0,
  type: 'directory',
  path: '/storage/test' },
{ name: 'asdf',
  size: 170,
  type: 'directory',
  path: '/storage/test/asdf' },
{ name: '2.txt',
  size: 0,
  type: 'file',
  path: '/storage/test/asdf/2.txt' }]

There could be any number of arbitrary path's, this is the result of iterating through files and folders within a directory.

What I'm trying to do is determine the 'root' node of these. Ultimately, this will be stored in mongodb and use materialized path to determine it's relationships.

In this example, /storage/test is a root with no parent. /storage/test/asdf has the parent of /storage/test which is the parent to /storage/test/asdf/2.txt.

My question is, how would you go about iterating through this array, to determine the parent's and associated children? Any help in the right direction would be great!

Thank you

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about node.js