简体   繁体   English

从对象中获取所有孩子的名字

[英]get all children names from object

How can I get all names from this object?如何从此对象中获取所有名称?

var familyTree = {name: 'Alex',
    children:[
        {name: 'Ricky', 
            children:'[...]'}
        {name: 'John', 
            children:[{name: 'Tom', 
                children: '[...]'}]}]};

That it would execute Alex Ricky John Tom.它将处决亚历克斯瑞奇约翰汤姆。

You could write a simple recursive function that will traverse the contents of your tree:您可以编写一个简单的递归函数来遍历树的内容:

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);

For the more flexible case where you want to return an array instead of just logging to console, here is another approach that recursively accumulates an array with depth-first traversal and argument passing:对于更灵活的情况,您希望返回数组而不是仅记录到控制台,这里是另一种方法,它使用深度优先遍历和参数传递递归地累加数组:

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;
}

Here's another approach that's written in more of a functional style:这是另一种以函数式风格编写的方法:

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);
    })
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM