遍历对象的javascript [英] javascript traversing through an object

查看:46
本文介绍了遍历对象的javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态创建的对象.这是一个简单的例子:

I have an object that is dynamically created. Here's a simple example:

global.data {
    children: [
        0: {
            children:  [
                0: {
                   children: value 
                }
            ]
        }
    ]

}

我想做的是检查对象(global.data)是否具有'children'属性,从中获取属性,然后将该对象('children')通过循环发送回去,以查看其是否具有'children'属性.自己的孩子"的财产.我希望它继续前进,直到没有更多的孩子"可以穿越为止.

What I want to do is check if the object (global.data) has a property of 'children', grab properties from it, and send that object ('children') back through the loop to see if it has a property of 'children' of it's own. I want it to keep going until there are no more 'children' left to traverse though.

推荐答案

运行一会儿循环,直到达到最深. jsfiddle

Run a while loop till it reaches to deepest. jsfiddle

global = {};
global.data = {
    children: [
         {
            children:  [
                 {
                   children: "value"
                }
            ]
        }
    ]
}

var obj = global.data;

while( typeof obj == 'object' && typeof obj.children == 'object'){
  obj = obj.children[0];
}
obj = obj.children ? obj.children  : obj;​
 // at this point obj is either undefined or has no children property. 

这篇关于遍历对象的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆