从 object 中获取所有 children 个名字
get all children names from object
如何从 object 中获取所有名称?
var familyTree = {name: 'Alex',
children:[
{name: 'Ricky',
children:'[...]'}
{name: 'John',
children:[{name: 'Tom',
children: '[...]'}]}]};
它会处决 Alex Ricky John Tom。
您可以编写一个简单的递归函数来遍历树的内容:
var familyTree = {
name: 'Alex',
children: [
{
name: 'Ricky',
children: [ ]
},
{
name: 'John',
children: [
{
name: 'Tom',
children: [ ]
}
]
}
]
};
var traverse = function(tree) {
console.log(tree.name);
for (var i = 0; i < tree.children.length; i++) {
traverse(tree.children[i]);
}
};
traverse(familyTree);
对于更灵活的情况,你想要 return 一个数组而不是仅仅记录到控制台,这里是另一种递归累积数组的方法,深度优先遍历和参数传递:
function storeNames(tree, names) {
(names = names || []).push(tree.name);
for(var i = 0; i < tree.children.length; i++) {
storeNames(tree.children[i], names);
}
return names;
}
这是另一种以函数式风格编写的方法:
function storeNames(tree) {
return Array.prototype.concat(tree.name,
tree.children.map(function(child) {
return storeNames(child);
}).reduce(function(flattenedArr, nestedArr) {
return flattenedArr.concat(nestedArr);
})
);
}
如何从 object 中获取所有名称?
var familyTree = {name: 'Alex',
children:[
{name: 'Ricky',
children:'[...]'}
{name: 'John',
children:[{name: 'Tom',
children: '[...]'}]}]};
它会处决 Alex Ricky John Tom。
您可以编写一个简单的递归函数来遍历树的内容:
var familyTree = {
name: 'Alex',
children: [
{
name: 'Ricky',
children: [ ]
},
{
name: 'John',
children: [
{
name: 'Tom',
children: [ ]
}
]
}
]
};
var traverse = function(tree) {
console.log(tree.name);
for (var i = 0; i < tree.children.length; i++) {
traverse(tree.children[i]);
}
};
traverse(familyTree);
对于更灵活的情况,你想要 return 一个数组而不是仅仅记录到控制台,这里是另一种递归累积数组的方法,深度优先遍历和参数传递:
function storeNames(tree, names) {
(names = names || []).push(tree.name);
for(var i = 0; i < tree.children.length; i++) {
storeNames(tree.children[i], names);
}
return names;
}
这是另一种以函数式风格编写的方法:
function storeNames(tree) {
return Array.prototype.concat(tree.name,
tree.children.map(function(child) {
return storeNames(child);
}).reduce(function(flattenedArr, nestedArr) {
return flattenedArr.concat(nestedArr);
})
);
}