array-to-tree
Advanced tools
Comparing version
16
index.js
'use strict'; | ||
var util = require('util'); | ||
@@ -8,2 +7,13 @@ var exists = function(obj, key) { | ||
var extend = function(destination, source) { | ||
for (var property in source) { | ||
destination[property] = source[property]; | ||
} | ||
return destination; | ||
} | ||
var isArray = Array.isArray || function(obj) { | ||
return toString.call(obj) === '[object Array]'; | ||
}; | ||
var createTree = function(array, rootNodes, customID) { | ||
@@ -62,3 +72,3 @@ var tree = []; | ||
module.exports = function arrayToTree(options) { | ||
options = util._extend({ | ||
options = extend({ | ||
parentProperty: 'parent_id', | ||
@@ -72,3 +82,3 @@ data: [], | ||
if (!util.isArray(data)) { | ||
if (!isArray(data)) { | ||
throw new Error('Expected an object but got an invalid argument'); | ||
@@ -75,0 +85,0 @@ } |
{ | ||
"name": "array-to-tree", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "Convert a plain array of nodes (with pointers to parent nodes) to a tree", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -13,8 +13,10 @@ # array-to-tree [](https://travis-ci.org/alferov/array-to-tree) | ||
## Basic Usage | ||
## Usage | ||
### Basic | ||
```js | ||
var arrayToTree = require('array-to-tree'); | ||
var navigation = [{ | ||
var data = [{ | ||
id: 1, | ||
@@ -37,2 +39,4 @@ name: "Portfolio", | ||
var tree = arrayToTree({ data: data }); | ||
/* | ||
@@ -46,7 +50,44 @@ * Output: | ||
var navigationTree = arrayToTree({ data: navigation }); | ||
``` | ||
## Documentation | ||
### With Custom Attributes | ||
```js | ||
var arrayToTree = require('array-to-tree'); | ||
var data = [{ | ||
_id: 'ec654ec1-7f8f-11e3-ae96-b385f4bc450c', | ||
name: "Portfolio", | ||
parent: null | ||
}, { | ||
_id: 'ec666030-7f8f-11e3-ae96-0123456789ab', | ||
name: "Web Development", | ||
parent: 'ec654ec1-7f8f-11e3-ae96-b385f4bc450c' | ||
}, { | ||
_id: 'ec66fc70-7f8f-11e3-ae96-000000000000', | ||
name: "Recent Works", | ||
parent: 'ec666030-7f8f-11e3-ae96-0123456789ab' | ||
}, { | ||
_id: '32a4fbed-676d-47f9-a321-cb2f267e2918', | ||
name: "About Me", | ||
parent: null | ||
}]; | ||
var tree = arrayToTree({ | ||
parentProperty: 'parent', | ||
customID: '_id' | ||
data: data | ||
}); | ||
/* | ||
* Output: | ||
* Portfolio | ||
* Web Development | ||
* Recent Works | ||
* About Me | ||
*/ | ||
``` | ||
## API | ||
### `arrayToTree(options)` | ||
@@ -53,0 +94,0 @@ Convert a plain array of nodes (with pointers to parent nodes) to a tree. |
9887
9.87%207
4.02%105
64.06%