简体   繁体   English

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

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

There is n number of parent and child in an object 一个对象中有n个父级和子级

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

foo(obj)                        

Write a function to get output as ['one', 'two, 'three', ...] 编写一个函数以将输出形式为['one', 'two, 'three', ...]

you should use a recursive function 您应该使用递归函数

var result = [];

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

searchChildren(obj);

https://jsfiddle.net/zrbfm9ud/ https://jsfiddle.net/zrbfm9ud/

This is one way to do it, basically you return and have function call itself again. 这是一种实现方法,基本上您可以返回并再次调用函数本身。 Kinda like a loop. 有点像循环。

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,[]);

Use a while loop to iterate through each level of your object until object.child cannot be found: 使用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'] 

You could use a generator and curry the object and the numbers, you want. 您可以使用生成器并根据需要修改对象和数字。

 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's answer seemed the best to me as it is really simple and efficient. @stackoverfloweth的答案对我来说似乎是最好的,因为它确实非常简单和有效。 But I think it can be even simpler, and also I made it include the last level: 但是我认为它甚至可以更简单,而且我使它包括最后一个级别:

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

You could try something like this 你可以尝试这样的事情

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

Use the following recursive function getAllNames() : 使用以下递归函数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, [])); 

Many answers check for the undefined child as the argument of the function to terminate the recursion. 许多答案都会将未定义的子项检查为函数的参数,以终止递归。 This means an extra call which can be avoided 这意味着可以避免额外的通话

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

This code will output array like this ["one", "two", "three"] 这段代码将输出像这样的数组["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; } 

Try this 尝试这个

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