如何通过添加键值使用每个循环从Object检索数据?

时间:2014-05-15 06:44:59

标签: jquery iteration underscore.js javascript-objects

我有一个url路径,从url我得到base和sub url的详细信息。使用所有这些网址,我想将控制器加载到网站。

我分别有ValidPath对象。我这样想:

var ValidPaths = {
        "green":{
            "url":"greenController.js",
            "lightgreen" :{
                "url":"lightGreenController.js",
                "floragreen":{
                    "url":"floragreenController.js"
                }
            }
        }
    }
var path = ["green"].concat("lightgreen/floragreen".split('/'));
var finArr = [];

_.each(path, function(str,key){
    label += '["'+str+'"]';
    console.log(ValidPaths+label['url']); // i am not getting proper console details.
})

但是我错了。 我在找我的finArr应该是这样的:

//should be [ {"label":"green","url":"greenController.js"}, {"label":"lightgreen","url":"lightGreenController.js"},{"label":"floragreen","url":"floragreenController.js"}]

所以我可以通过temp引擎进行迭代。谁能告诉我这里的错误是什么?

Demo Here

2 个答案:

答案 0 :(得分:1)

$(function() {
   var ValidPaths = {
        "green":{
            "url":"greenController.js",
            "lightgreen" :{
                "url":"lightGreenController.js",
                "floragreen":{
                    "url":"floragreenController.js"
                }
            }
        }
    },
    finArr = [],
       getNode = function(color, obj ) {
           var oPath = {}, i = 0;
           oPath.label = color;
           for( clr in obj ) {
               if( i === 0 ) {
                   oPath.url = obj[ clr ];
                   finArr.push( oPath );
               } else if( i === 1 ) {
                   getNode( clr, obj[ clr ] );
               }
               i++;
           }
       };
    for( clr in ValidPaths) {
        getNode( clr, ValidPaths[clr] );
    }
    console.log( finArr ); 
});

JSFiddle Demo

This version是我能得到的最短的。任何更短的我遇到的' Uncaught RangeError:超出最大调用堆栈大小'错误

答案 1 :(得分:0)

感谢user3558931,

 var paths = [path].concat(subPath.split('/')),
                    arr = [],prePath=ValidPaths;

                 function pathFinder (path,i){
                    if(prePath[path]){
                        arr.push({"label":path,"url":prePath[path]['url']});
                        prePath = prePath[path];
                    } else{
                        console.log("there is no path like " + path + "in ValidPaths");
                    }
                    return arr;
                }

                _.map(paths, function(root,i){
                    return pathFinder(root,i);
                });

                console.log("breadCrumb", arr);