get all children names from object

匆匆过客 提交于 2019-12-13 10:53:55

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/33588073/get-all-children-names-from-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!