Converts row data (in JSON/associative array format or flat array format) to object/tree structure based on simple column naming conventions.

Installation

npm install treeize

Because APIs usually require data in a deep object graph/collection form, but SQL results (especially heavily joined data), excel, csv, and other flat data sources that we're often forced to drive our applications from represent data in a very "flat" way. Treeize takes this flattened data and based on simple column/attribute naming conventions, remaps it into a deep object graph - all without the overhead/hassle of hydrating a traditional ORM.

What it does...

var peopleData = [ { ' name ' : ' John Doe ' , ' age ' : 34 , ' pets:name ' : ' Rex ' , ' pets:type ' : ' dog ' , ' pets:toys:type ' : ' bone ' } , { ' name ' : ' John Doe ' , ' age ' : 34 , ' pets:name ' : ' Rex ' , ' pets:type ' : ' dog ' , ' pets:toys:type ' : ' ball ' } , { ' name ' : ' Mary Jane ' , ' age ' : 19 , ' pets:name ' : ' Mittens ' , ' pets:type ' : ' kitten ' , ' pets:toys:type ' : ' yarn ' } , { ' name ' : ' Mary Jane ' , ' age ' : 19 , ' pets:name ' : ' Fluffy ' , ' pets:type ' : ' cat ' } ] ; var peopleData = [ [ ' name ' , ' age ' , ' pets:name ' , ' pets:type ' , ' pets:toys:type ' ] , [ ' John Doe ' , 34 , ' Rex ' , ' dog ' , ' bone ' ] , [ ' John Doe ' , 34 , ' Rex ' , ' dog ' , ' ball ' ] , [ ' Mary Jane ' , 19 , ' Mittens ' , ' kitten ' , ' yarn ' ] , [ ' Mary Jane ' , 19 , ' Fluffy ' , ' cat ' , null ] ] ; var Treeize = require ( ' treeize ' ) ; var people = new Treeize ( ) ; people . grow ( peopleData ) ; people . getData ( ) == [ { name : ' John Doe ' , age : 34 , pets : [ { name : ' Rex ' , type : ' dog ' , toys : [ { type : ' bone ' } , { type : ' ball ' } ] } ] } , { name : ' Mary Jane ' , age : 19 , pets : [ { name : ' Mittens ' , type : ' kitten ' , toys : [ { type : ' yarn ' } ] } , { name : ' Fluffy ' , type : ' cat ' } ] } ] ;

API Index

1. get/set options (optional)

options([options]) - getter/setter for options

- getter/setter for options getOptions() - returns options

- returns options setOptions(options) - merges new [options] with existing

- merges new with existing resetOptions() - resets options to defaults

2a. set data signature manually if needed (optional)

signature([row], [options]) - getter/setter for signature definitions

- getter/setter for signature definitions getSignature() - returns currently defined signature

- returns currently defined signature setSignature(row, [options]) - sets signature using a specific row of data/headers (preserves signature between data sets if uniformity option is enabled)

- sets signature using a specific row of data/headers (preserves signature between data sets if uniformity option is enabled) clearSignature() - clear signature between data sets (only needed when previously defined a uniform signature via setSignature )

2b. grow tree from data set(s)

grow(data, [options]) - grow flat data , with optional local [options]

3. retrieve transformed data

getData() - gets current tree data

- gets current tree data getSeedData() - gets original, flat data

* misc/internal methods

getStats() - returns object with growth statistics

API

Getter/Setter for options. If options object is passed, this is identical to .setOptions(options) and returns self (chainable). If no options are passed, this is identical to .getOptions() and returns current options as object.

Sets options globally for the Treeize instance. This is an alias for .options(options) . Default options are as follows:

{ input : { delimiter : ' : ' , detectCollections : true , uniformRows : false , } , output : { prune : true , objectOverwrite : true , resultsAsObject : false , } }

For example, to change the delimiter and enable output logging, you would use the following:

. setOptions ( { input : { delimiter : ' | ' } } ) ;

Available Options

input.delimiter This sets the delimiter to be used between path segments (e.g. the ":" in "children:mother:name"). View test example

input.detectCollections Enables/disables the default behavior of turning plural path segments (e.g. "subjects" vs. "subject") into collections instead of object paths. Note: In order to properly merge multiple rows into the same collection item, the collection must have a base-level attribute(s) acting as a signature. View test example (enabled) | or (disabled)

input.uniformRows By default row uniformity is disabled to allow the most flexible data merging. This means each and every row of data that is processed (unless flat array-of-array data) will be analyzed and mapped individually into the final structure. If your data rows have uniform attributes/columns, disable this for a performance increase.

output.prune Removes blank/empty nodes in the structure. This is enabled by default to prevent sparse data sets from injecting blanks and nulls everywhere in your final output. If nulls are important to preserve, disable this. View test example

output.objectOverwrite To allow for merging objects directly onto existing placeholder values (e.g. foreign key ids), this is enabled by default. View test example

output.resultsAsObject This creates a single root object (instead of the default array of objects). View test example

Returns the current global options (as object). View example format

Resets all global options to original defaults and returns self (chainable).

Getter/Setter for row signatures. If options object is passed, this is identical to .setSignature(options) and returns self (chainable). If no options are passed, this is identical to .getSignature() and returns currently defined signature as object.

Manually defines the signature for upcoming data sets from argument row , with optional options . The row may be either in object (key/value) form or flat array form (array of paths). This method is only required if sharing a single signature across multiple data sources (when merging homogeneous data sets), or when the data itself has no header information (for instance, with bulk flat array-of-values data). Returns self (chainable).

. setSignature ( { ' id ' : 1 , ' name:first ' : ' Kevin ' , ' name:last ' : ' Whitley ' , ' hobbies:name ' : ' photography ' ' hobbies:years ' : 12 } ) . setSignature ( [ ' id ' , ' name:first ' , ' name:last ' , ' hobbies:name ' , ' hobbies:years ' ] )

Returns currently defined signature. For internal use only.

Clears currently-defined signature if previously set via setSignature(row) , and returns self (chainable). This is only required between data sets if signature auto-detection should be re-enabled. It is unlikely that you will need to use this.

Returns current data tree.

var tree = new Treeize ( ) ; tree . grow ( [ { ' foo ' : ' bar ' , ' logs:a ' : 1 } , { ' foo ' : ' bar ' , ' logs:a ' : 2 } , { ' foo ' : ' baz ' , ' logs:a ' : 3 } , ] ) ; console . log ( tree . getData ( ) ) ;

Returns original, flat data.

var tree = new Treeize ( ) ; tree . grow ( [ { ' foo ' : ' bar ' , ' logs:a ' : 1 } , { ' foo ' : ' bar ' , ' logs:a ' : 2 } , { ' foo ' : ' baz ' , ' logs:a ' : 3 } ] ) ; console . log ( tree . getSeedData ( ) ) ;

Returns current growth statistics (e.g. number of sources process, number of rows, etc). Output and format subject to change - use at your own risk.

The grow(data, [options]) method provides the core functionality of Treeize. This method expands flat data (of one or more sources) into the final deep tree output. Each attribute path is analyzed for injection into the final object graph.

Path Naming

Each column/attribute of each row will dictate its own destination path using the following format:

{ ' path1:path2:pathX:attributeName ' : [ value ] }

Each "path" (up to n-levels deep) is optional and represents a single object node if the word is singular, or a collection if the word is plural (with optional +/- override modifiers). For example, a "favoriteMovie:name" path will add a "favoriteMovie" object to its path - where "favoriteMovies:name" would add a collection of movies (complete with a first entry) instead. For root nodes, include only the attribute name without any preceding paths. If you were creating a final output of a book collection for instance, the title of the book would likely be pathless as you would want the value on the high-level books collection.

It's important to note that each row will create or find its path within the newly transformed output being created. Your flat feed may have mass-duplication, but the results will not.

Merging Multiple Data Sources

Treeize was designed to merge from multiple data sources of both attribute-value and array-of-value format (as long as signatures are provided in some manner), including ones with varying signatures.

var Treeize = require ( ' treeize ' ) ; var arrayOfObjects = require ( ' somesource1.js ' ) ; var arrayOfValues = require ( ' somesource2.js ' ) ; var tree = new Treeize ( ) ; tree . grow ( arrayOfObjects ) . grow ( arrayOfValues ) ;

How to manually override the default pluralization scheme for collection-detection

In the rare (but possible) case that plural/singular node names are not enough to properly detect collections, you may add specific overrides to the node name, using the + (for collections) and - (for singular objects) indicators.

{ ' name ' : ' Bird ' , ' attributes:legs ' : 2 , ' attributes:hasWings ' : true } [ { name : ' Bird ' , attributes : [ { legs : 2 , hasWings : true } ] } ] { ' name ' : ' Bird ' , ' attributes-:legs ' : 2 , ' attributes-:hasWings ' : true } [ { name : ' Bird ' , attributes : { legs : 2 , hasWings : true } } ]

Specifying Your Own Key/Blueprint For Collections

By default, all known attributes of a collection node level define a "blueprint" by which to match future rows. For example, in a collection of people, if both name and age attributes are defined within each row, future rows will require both the name and age values to match for the additional information to be merged into that record. To override this default behavior and specify your own criteria, simply mark each required attribute with a leading or tailing * modifier.

[ { ' date ' : ' 1/1/2014 ' , ' temperatureF ' : 90 , ' temperatureC ' : 32 } , { ' date ' : ' 1/1/2014 ' , ' humidity ' : . 1 } ] [ { date : ' 1/1/2014 ' , temperatureF : 90 , temperatureC : 32 } , { date : ' 1/1/2014 ' , humidity : 0 . 1 } ] [ { ' date* ' : ' 1/1/2014 ' , ' temperatureF ' : 90 , ' temperatureC ' : 32 } , { ' date* ' : ' 1/1/2014 ' , ' humidity ' : . 1 } ] [ { date : ' 1/1/2014 ' , temperatureF : 90 , temperatureC : 32 , humidity : 0 . 1 } ]

Notes

Each attribute name of the flat data must consist of the full path to its node & attribute, seperated by the delimiter. id suggests an id attribute on a root element, whereas name:first implies a first attribute on a name object within a root element.

suggests an attribute on a root element, whereas implies a attribute on a object within a root element. To imply a collection in the path/attribute-name, use a plural name (e.g. "subjects" instead of "subject"). Otherwise, use a singular name for a singular object.

Use a : delimiter (default) to seperate path segments. To change this, modify the input.delimiter option.

Examples

In this short series of examples, we'll take a standard "join dump", originally keyed (via attribute names) to organize by movie - and demonstrate how other organizations can be easily derived from the same original feed... by simply modifying the column/attribute names in the output.

Example 1

In this example, we'll take our dump (as if from a CSV or SQL result) - and name the keys to group by movies (as if for an /api/movies ).

var movieData = [ { ' title ' : ' The Prestige ' , ' director ' : ' Christopher Nolan ' , ' actors:name ' : ' Christian Bale ' , ' actors:as ' : ' Alfred Borden ' } , { ' title ' : ' The Prestige ' , ' director ' : ' Christopher Nolan ' , ' actors:name ' : ' Hugh Jackman ' , ' actors:as ' : ' Robert Angier ' } , { ' title ' : ' The Dark Knight Rises ' , ' director ' : ' Christopher Nolan ' , ' actors:name ' : ' Christian Bale ' , ' actors:as ' : ' Bruce Wayne ' } , { ' title ' : ' The Departed ' , ' director ' : ' Martin Scorsese ' , ' actors:name ' : ' Leonardo DiCaprio ' , ' actors:as ' : ' Billy ' } , { ' title ' : ' The Departed ' , ' director ' : ' Martin Scorsese ' , ' actors:name ' : ' Matt Damon ' , ' actors:as ' : ' Colin Sullivan ' } ] ; var Treeize = require ( ' treeize ' ) ; var movies = new Treeize ( ) ; movies . grow ( movieData ) ;

Example 2

Taking the same feed, but modifying the target paths through the attribute/column names we can completely transform the data (as you would for another API endpoint, for example). This time we'll organize the data by actors, as you would for and endpoint like /api/actors .

Notice the feed is left unchanged - only the attribute names have been modified to define their new target path. In this case, by changing the base node to the actor name (instead of the movie name), we group everything by actor at a high level.

var moviesDump = [ { ' movies:title ' : ' The Prestige ' , ' movies:director ' : ' Christopher Nolan ' , ' name ' : ' Christian Bale ' , ' movies:as ' : ' Alfred Borden ' } , { ' movies:title ' : ' The Prestige ' , ' movies:director ' : ' Christopher Nolan ' , ' name ' : ' Hugh Jackman ' , ' movies:as ' : ' Robert Angier ' } , { ' movies:title ' : ' The Dark Knight Rises ' , ' movies:director ' : ' Christopher Nolan ' , ' name ' : ' Christian Bale ' , ' movies:as ' : ' Bruce Wayne ' } , { ' movies:title ' : ' The Departed ' , ' movies:director ' : ' Martin Scorsese ' , ' name ' : ' Leonardo DiCaprio ' , ' movies:as ' : ' Billy ' } , { ' movies:title ' : ' The Departed ' , ' movies:director ' : ' Martin Scorsese ' , ' name ' : ' Matt Damon ' , ' movies:as ' : ' Colin Sullivan ' } ] ; var Treeize = require ( ' treeize ' ) ; var actors = new Treeize ( ) ; actors . grow ( moviesData ) ;

Changelog