繁体   English   中英

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

[英]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/

这是一种实现方法,基本上您可以返回并再次调用函数本身。 有点像循环。

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'] 

您可以使用生成器并根据需要修改对象和数字。

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

@stackoverfloweth的答案对我来说似乎是最好的,因为它确实非常简单和有效。 但是我认为它甚至可以更简单,而且我使它包括最后一个级别:

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

你可以尝试这样的事情

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

使用以下递归函数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 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; } 

尝试这个

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

暂无
暂无

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

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