Skip to content

Instantly share code, notes, and snippets.

@lichenbuliren
Created April 27, 2017 15:57
Show Gist options
  • Save lichenbuliren/e907dd8f8f50baef30c3bfb54a87dbe3 to your computer and use it in GitHub Desktop.
Save lichenbuliren/e907dd8f8f50baef30c3bfb54a87dbe3 to your computer and use it in GitHub Desktop.
常见数据结构遍历
var data = {
id: 1,
name: 'first',
children: [{
id: 2,
name: 'first-1',
children: false
}, {
id: 3,
name: 'first-2',
children: false
}, {
id: 4,
name: 'first-3',
children: [{
id: 22,
name: 'first-3-1',
children: false
}, {
id: 33,
name: 'first-3-2',
children: false
}]
}]
}
var child = getNodeData(data, 22);
console.log(child);
function getNodeData(node, id) {
if (node && node.id === id) return node;
if (node && node.children) {
for (var i = 0; i < node.children.length; i++) {
var tmp = getNodeData(node.children[i], id);
if (tmp) {
return tmp;
} else {
continue;
}
}
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment