Javascript 递归地遍历对象(树)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2549320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
looping through an object (tree) recursively
提问by Val
Is there a way (in jQuery or JavaScript) to loop through each object and it's children and grandchildren and so on?
有没有办法(在 jQuery 或 JavaScript 中)循环遍历每个对象及其子对象和孙子对象等等?
If so... can I also read their name?
如果是这样……我也可以读一下他们的名字吗?
Example:
例子:
foo :{
bar:'',
child:{
grand:{
greatgrand: {
//and so on
}
}
}
}
so the loop should do something like this...
所以循环应该做这样的事情......
loop start
if(nameof == 'child'){
//do something
}
if(nameof == 'bar'){
//do something
}
if(nameof =='grand'){
//do something
}
loop end
回答by Andy E
You're looking for the for...inloop:
你正在寻找for...in循环:
for (var key in foo)
{
if (key == "child")
// do something...
}
Be aware that for...inloops will iterate over any enumerable properties, including those that are added to the prototype of an object. To avoid acting on these properties, you can use the hasOwnPropertymethod to check to see if the property belongs only to that object:
请注意,for...in循环将遍历任何可枚举的属性,包括添加到对象原型中的属性。为了避免对这些属性进行操作,您可以使用该hasOwnProperty方法来检查该属性是否仅属于该对象:
for (var key in foo)
{
if (!foo.hasOwnProperty(key))
continue; // skip this property
if (key == "child")
// do something...
}
Performing the loop recursively can be as simple as writing a recursive function:
以递归方式执行循环可以像编写递归函数一样简单:
// This function handles arrays and objects
function eachRecursive(obj)
{
for (var k in obj)
{
if (typeof obj[k] == "object" && obj[k] !== null)
eachRecursive(obj[k]);
else
// do something...
}
}
回答by Rick
If you want to get back a tree of relationships you can use Object.keys recursively.
如果你想找回关系树,你可以递归地使用 Object.keys。
function paths(item) {
function iter(r, p) {
var keys = Object.keys(r);
if (keys.length) {
return keys.forEach(x => iter(r[x], p.concat(x)));
}
result.push([p])
}
var result = [];
iter(item, []);
return result;
}
var data = {
foo: {
bar: '',
child: {
grand: {
greatgrand: {}
}
}
}
}
console.log(paths(data));
回答by Jo?o Pimentel Ferreira
You can have a recursive function with a parse function built within it.
你可以有一个递归函数,其中内置了一个解析函数。
function parseObjectProperties (obj, parse) {
for (var k in obj) {
if (typeof obj[k] === 'object' && obj[k] !== null) {
parseObjectProperties(obj[k], parse)
} else if (obj.hasOwnProperty(k)) {
parse(obj[k])
}
}
}
I use the fooobject of the OP, here how it works
我使用fooOP的对象,这里是它是如何工作的
var foo = {
bar:'a',
child:{
b: 'b',
grand:{
greatgrand: {
c:'c'
}
}
}
}
// use this recursive function with a parse funciton
function parseObjectProperties (obj, parse) {
for (var k in obj) {
if (typeof obj[k] === 'object' && obj[k] !== null) {
parseObjectProperties(obj[k], parse)
} else if (obj.hasOwnProperty(k)) {
parse(obj[k])
}
}
}
//***
// then apply to the property the task you want, in this case just console
parseObjectProperties(foo, function(prop) {
console.log(prop)
})

