Skip to content

Instantly share code, notes, and snippets.

@jhyang12345
Created July 11, 2017 05:32
Show Gist options
  • Save jhyang12345/3665276355dbacb38cb4ae2e4916f340 to your computer and use it in GitHub Desktop.
Save jhyang12345/3665276355dbacb38cb4ae2e4916f340 to your computer and use it in GitHub Desktop.
root = [{
"id": 1,
"name": "Yong",
"phone": "010-2786-9902",
"type": "sk",
"childnode": [{
"id": 11,
"name": "echo",
"phone": "010-3923-1333",
"type": "kt",
"childnode": [{
"id": 115,
"name": "hary",
"phone": "010-2786-9302",
"type": "sk",
"childnode": [{
"id": 1159,
"name": "pobi",
"phone": "010-9302-0009",
"type": "kt",
"childnode": [{
"id": 11592,
"name": "cherry",
"phone": "010-1223-9932",
"type": "lg",
"childnode": []
},
{
"id": 11595,
"name": "solvin",
"phone": "010-534-7843",
"type": "sk",
"childnode": []
}
]
}]
},
{
"id": 116,
"name": "kim",
"phone": "010-3796-1102",
"type": "kt",
"childnode": [{
"id": 1168,
"name": "hani",
"phone": "010-1223-6713",
"type": "sk",
"childnode": [{
"id": 11689,
"name": "ho",
"phone": "010-4434-4534",
"type": "kt",
"childnode": [{
"id": 116890,
"name": "wonsuk",
"phone": "010-3434-1302",
"type": "kt",
"childnode": []
},
{
"id": 1168901,
"name": "chulsu",
"phone": "010-3100-9841",
"type": "sk",
"childnode": []
}
]
}]
}]
},
{
"id": 117,
"name": "hong",
"phone": "010-2786-9902",
"type": "lg",
"childnode": []
}
]
}]
}]
function traverseTree(root) {
var ret = [];
var stack = [];
var index = 0;
for(item of root) {
stack.push(item);
}
//console.log(stack);
while(index < stack.length) {
if(stack[index]["type"] == "sk") {
//console.log(stack[index]["name"]);
ret.push(stack[index]["name"]);
}
for(item of stack[index]["childnode"]) {
stack.push(item);
}
index++;
}
return ret;
}
console.log(traverseTree(root));
const resultObj = {};
function parse(obj, spec) {
var ret = [];
var stack = [];
var index = 0;
for(item of root) {
stack.push(item);
}
//console.log(stack);
while(index < stack.length) {
if(stack[index]["type"] == spec) {
//console.log(stack[index]["name"]);
ret.push(stack[index]["name"]);
}
for(item of stack[index]["childnode"]) {
stack.push(item);
}
index++;
}
resultObj[spec] = ret;
}
parse(root, "sk");
console.log(resultObj.sk);
parse(root, "kt");
console.log(resultObj.kt);
var bufferstack = [];
function dfs(obj, name) {
if(obj["type"] == name) {
bufferstack.push(obj["name"]);
}
for(val of obj["childnode"]) {
dfs(val, name);
}
return;
}
function mainDfs(arr, name) {
for(val of arr) {
dfs(val, name);
}
}
function parse2(obj, spec) {
mainDfs(obj, spec);
resultObj[spec] = bufferstack;
bufferstack = [];
}
parse2(root, "sk");
console.log(resultObj.sk);
parse2(root, "kt");
console.log(resultObj.kt);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment