迭代嵌套的JavaScript对象 [英] Iterate through Nested JavaScript Objects

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

问题描述

我正在尝试遍历嵌套对象以检索由字符串标识的特定对象。在下面的示例对象中,标识符字符串是label属性。我无法绕过如何遍历树以返回适当的对象。任何帮助或建议将不胜感激。

I'm trying to iterate through a nested object to retrieve a specific object identified by a string. In the sample object below, the identifier string is the "label" property. I can't wrap my head around how to iterate down through the tree to return the appropriate object. Any help or suggestions would be greatly appreciated.

var cars = 
    {
        label: 'Autos',
        subs:
            [
                {
                    label: 'SUVs',
                    subs: []
                },
                {
                    label: 'Trucks',
                    subs: [
                              {
                                label: '2 Wheel Drive',
                                subs: []
                              },
                              {
                                label: '4 Wheel Drive',
                                subs: [
                                          {
                                            label: 'Ford',                                        
                                            subs: []
                                          },
                                          {
                                            label: 'Chevrolet',
                                            subs: []                                      
                                          }
                                      ]                          
                              }
                          ]    
                },
                {
                    label: 'Sedan',
                    subs: []
                }
            ]
    }


推荐答案

您可以创建这样的递归函数来对汽车进行深度优先遍历 object。

You can create a recursive function like this to do a depth-first traversal of the cars object.

var findObjectByLabel = function(obj, label) {
    if(obj.label === label) { return obj; }
    for(var i in obj) {
        if(obj.hasOwnProperty(i)){
            var foundLabel = findObjectByLabel(obj[i], label);
            if(foundLabel) { return foundLabel; }
        }
    }
    return null;
};

可以像这样调用

findObjectByLabel(car, "Chevrolet");

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

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