Created
November 20, 2016 14:19
-
-
Save cohama/e37639754000e6ee3278ec13e0608ead to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint no-console: "off", no-unused-vars: "off" */ | |
var xs = [ | |
{id: 'A', pid: '', name: 'aaa'}, | |
{id: 'B', pid: '', name: 'bbb'}, | |
{id: 'C', pid: '', name: 'ccc'}, | |
{id: 'A-a', pid: 'A', name: 'aaa-aaa'}, | |
{id: 'A-b', pid: 'A', name: 'aaa-bbb'}, | |
{id: 'B-a', pid: 'B', name: 'bbb-aaa'}, | |
{id: 'B-b', pid: 'B', name: 'bbb-bbb'}, | |
{id: 'C-a', pid: 'C', name: 'ccc-aaa'}, | |
{id: 'C-a-a', pid: 'C-a', name: 'ccc-aaa-aaa'}, | |
{id: 'C-a-a-a', pid: 'C-a-a', name: 'ccc-aaa-aaa-aaa'}, | |
{id: 'C-a-a-b', pid: 'C-a-a', name: 'ccc-aaa-aaa-bbb'}, | |
{id: 'C-a-a-c', pid: 'C-a-a', name: 'ccc-aaa-aaa-ccc'}, | |
{id: 'C-a-b', pid: 'C-a', name: 'ccc-aaa-bbb'}, | |
{id: 'C-a-c', pid: 'C-a', name: 'ccc-aaa-ccc'}, | |
] | |
function buildTree(xs, cidKey, pidKey, childrenKey) { | |
var walk = function(root, pid) { | |
root[childrenKey] = xs | |
.filter(function(v) {return v[pidKey] == pid}) | |
.map(function(parent){return walk(parent, parent[cidKey])}) | |
return root | |
} | |
return walk({}, '')[childrenKey] | |
} | |
var tree = JSON.stringify(buildTree(xs, 'id', 'pid', 'children'), null, 2) | |
console.log(tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment