如何遍历对象的嵌套子对象并收集名称数组

How to iterate through nested children of an object and collect an array of names

一个对象中有n个父子

var obj={
    name:'one',
    child:{
        name:'two',
        child:{
            name:'three',
            child..
        }
    }
} 

foo(obj)                        

写一个函数得到输出为['one', 'two, 'three', ...]

你应该使用递归函数

var result = [];

function searchChildren(parent){
    if(parent.child){
        result.push(parent.name);
        searchChildren(parent.child);
    }
}

searchChildren(obj);

https://jsfiddle.net/zrbfm9ud/

你可以试试这样的

funtion f1(array, obj){
  if(obj){
   if(obj.name){
     array.push(obj.name);
   }
   if(obj.child){
     return f1(array, obj.child);
   }
 }
 return array;
}


funtion f2(array, obj){
  while(obj){
    if(obj.name){
      array.push(obj.name);
    }
    obj = obj.child;

   }

   return array;
}

function foo(obj){
 var array = [];
 //recursive version
 return f1(array, obj); 
 // non recursive version
 //return f2(array, obj);
}

foo(obj);

这是一种方法,基本上您 return 并让函数再次调用自身。有点像循环。

var obj={
    name:'one',
    child:{
        name:'two',
        child:{
            name:'three'
        }
    }
} 


function foo(obj, arr) {
  if (!obj) return arr;
  arr.push(obj.name);
  return foo(obj.child, arr);
}

var results = foo(obj,[]);

使用 while 循环遍历对象的每个级别,直到找不到 object.child

function foo(object) {
  var result = []
  while (object) {
    result.push(object.name)
    object = object.child
  }
  return result
}

var object = {
  name: 'one',
  child: {
    name: 'two',
    child: {
      name: 'three'
    }
  }
}

console.log(foo(object)) //=> ['one', 'two', 'three']

使用下面的递归函数getAllNames():

/**
 * Collects all `name` property values recursively
 *
 * @param o    an object
 * @param res  the resulting array
 * @returns {*|Array}
 */
function getAllNames(o, res) {
    var names = res || [];
    for (var k in o) {
        if (k === 'name') {
            names.push(o[k]);   // saving `name` value
        } else if(k === 'child' && typeof o[k] === 'object') {
            getAllNames(o[k], names);  // processing nested `child` object
        }
    }
    return names;
}

var obj = {
    name:'one',
    child:{
        name:'two',
        child:{
            name:'three',
            child: {
                name: 'four',
                child: {
                    name: 'five'
                }  
            }
        }
    }
};

console.log(getAllNames(obj, []));

您可以使用生成器并根据需要柯里化对象和数字。

function setObject(object) {
    return function* (n) {
        while (n--) {
            yield object.name;
            object = object.child;
        }
    }
}

var obj = { name: 'one', child: { name: 'two', child: { name: 'three', child: { name: 'four', child: { name: 'five' } } } } },
    getNumbers = setObject(obj);

console.log([...getNumbers(4)]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

许多答案检查未定义的 child 作为终止递归的函数的参数。这意味着可以避免额外的调用

function doit (obj, arr = []){
    arr.push(obj.name);
    return obj.child ? doit(obj.child, arr) : arr;
}

这段代码会输出这样的数组 ["one", "two", "three"]

var obj = {
  name: 'one',
  child: {
    name: 'two',
    child: {
      name: 'three'
    }
  }
}

var str = parser(obj);
var arr = str.substring(0, str.length - 1).split(";");

console.log(arr); // Output ["one", "two", "three"]

function parser(obj) {
  var text = obj.name + ";";
  if (obj.child) text += parser(obj.child);
  return text;
}

@Whosebugeth 的回答对我来说似乎是最好的,因为它非常简单高效。不过我觉得还可以再简单点,我还把最后一层加进去了:

var obj={
    name:'one',
    child:{
        name:'two',
        child:{
            name:'three'
        }
    }
} 

var res = [];
function search(obj){
    res.push(obj.name);
    !obj.child || search(obj.child);
}

search(obj);
console.log(res);

试试这个

var string = foo(obj);
var array = str.substring(0, str.length - 1).split(",");

console.log(array);

function foo(obj) {
  var total= obj.name + ",";
  if (obj.child !=null) total= total+ foo(obj.child);
  return total;
}