javascript复杂递归

时间:2013-11-06 11:34:58

标签: javascript json recursion

鉴于以下是数据阵列中的数据。我在下面的代码中所做的是,根据给定的数据,我必须以特殊格式构造json,我也在下面给出。

//code start here
   var hierarchy={};
    hierarchy.name="Hierarchy";
    hierarchy.children=[{"name":"","children":[{"name":"","children":[]}]}];
    var countryindex;
    var flagExist=false;
    var data = [
        {country :"America", city:"Kansas", employe:'Jacob'},
        {country :"Pakistan", city:"Lahore", employe:'tahir'},
        {country :"Pakistan", city:"Islamabad", employe:'fakhar'} ,
        {country :"Pakistan", city:"Lahore", employe:'bilal'},
        {country :"India", city:"d", employe:'ali'}  ,
        {country :"Pakistan", city:"Karachi", employe:'eden'},
        {country :"America", city:"Kansas", employe:'Jeen'}  ,
        {country :"India", city:"Banglore", employe:'PP'} ,
        {country :"India", city:"Banglore", employe:'JJ'}  ,

    ];


    for(var i=0;i<data.length;i++)
    {


        for(var j=0;j<hierarchy.children.length;j++)
        {
            //for checking country match
            if(hierarchy.children[j].name==data[i].country)
            {
                countryindex=j;
                flagExist=true;
                break;

            }

        }

        if(flagExist)//country match now no need to add new country just add city in it
        {
            var cityindex;
            var cityflag=false;
            //hierarchy.children[countryindex].children.push({"name":data[i].city,"children":[]})
            //if(hierarchy.children[index].children!=undefined)
            for(var k=0;k< hierarchy.children[countryindex].children.length;k++)
            {
                //for checking city match
                if(hierarchy.children[countryindex].children[k].name==data[i].city)
                {
                    // hierarchy.children[countryindex].children[k].children.push({"name":data[i].employe})
                    cityflag=true;
                    cityindex=k;
                    break;
                }

            }
            if(cityflag)//city match now add just empolye at that city index
            {
                hierarchy.children[countryindex].children[cityindex].children.push({"name":data[i].employe});

                cityflag=false;
            }
            else//no city match so add new with employe also as this is new city so its emplye will be 1st
            {
                hierarchy.children[countryindex].children.push({"name":data[i].city,children:[{"name":data[i].employe}]});
                //same as above
                //hierarchy.children[countryindex].children[length-1].children.push({"name":data[i].employe});


            }
            flagExist=false;
        }
        else{ //no country match adding new country //with city also as this is new city of new country
            console.log("sparta");
            hierarchy.children.push({"name":data[i].country,"children":[{"name":data[i].city,"children":[{"name":data[i].employe}]}]});

            // hierarchy.children.children.push({"name":data[i].city,"children":[]});
        }


        //console.log(hierarchy);
    }
    hierarchy.children.shift();
 var j=JSON.stringify(hierarchy);

//code ends here

//这里是我从代码

成功形成的json
{

"name":"Hierarchy",
"children":[
{
"name":"America",
"children":[
{
"name":"Kansas",
"children":[{"name":"Jacob"},{"name":"Jeen"}]}]},
{
"name":"Pakistan",
"children":[
{
"name":"Lahore",
"children":
[
{"name":"tahir"},{"name":"bilal"}]},
{
"name":"Islamabad",
"children":[{"name":"fakhar"}]},
{
"name":"Karachi",
"children":[{"name":"eden"}]}]},
{
"name":"India",
"children":
[
{
"name":"d",
"children":
[
{"name":"ali"}]},
{
"name":"Banglore",
"children":[{"name":"PP"},{"name":"JJ"}]}]}]}

现在orignal问题是,目前我正在为三个数组的数据解决这个问题,我必须去3个嵌套循环现在我想优化这个解决方案,以便如果对象的数据数组有超过3个键说5  {country:“America”,state:“NewYork”,city:“newYOrk”,street:“elm”,employe:'Jacob'}, 或者超过我的解决方案将无法工作,我无法决定将来会有多少键,所以我认为递归可能最适合这里。但我在写复说方面很可怕,案件也很复杂。一些很棒的程序员可以帮我写复发或建议其他一些解决方案。

1 个答案:

答案 0 :(得分:2)

我创建了一个可以帮助你的函数,递归并支持任何长度级别,但代码有点长

  var data = [
        {country :"America", city:"Kansas", employe:'Jacob'},
        {country :"Pakistan", city:"Lahore", employe:'tahir'},
        {country :"Pakistan", city:"Islamabad", employe:'fakhar'} ,
        {country :"Pakistan", city:"Lahore", employe:'bilal'},
        {country :"India", city:"d", employe:'ali'}  ,
        {country :"Pakistan", city:"Karachi", employe:'eden'},
        {country :"America", city:"Kansas", employe:'Jeen'}  ,
        {country :"India", city:"Banglore", employe:'PP'} ,
        {country :"India", city:"Banglore", employe:'JJ'}  ,

    ];


function groupByLevel( source, levels, config ){
    config = ( typeof config == "object" && config ) || {};

    var internalConfig = {
        keyName: config.keyName || "name",
        collectionName: config.collectionName || "children"
    };

    var hierarchy = {};
    hierarchy[internalConfig.keyName] = "Hierarchy";
    hierarchy[internalConfig.collectionName] = source;

    var sourceArray = [hierarchy];

    for(var i = 0; i < levels.length; i++){

        var newSourceArray = [];

        for(var j = 0; j < sourceArray.length; j++){

            var oldArray = sourceArray[j][internalConfig.collectionName];
            var newArray = groupBy(oldArray, levels[i], internalConfig);            
            sourceArray[j][internalConfig.collectionName] = newArray;
            for(var l = 0; l < newArray.length; l++){
                newSourceArray.push(newArray[l]);
            }
        }
        sourceArray = newSourceArray;
    }
    return hierarchy;
}


function duplicate(obj){
    var newObj = {};
    for(var i in obj) newObj[i] = obj[i];
    return newObj;
}

function objlength(obj){
    var length = 0;
    for(var i in obj) length++;
    return length
}

function groupBy(array, key, config){
    var group = {};

    for(var i = 0; i < array.length; i++){

        var item = array[i];
        var currentKey = item[key];     

        if( ! group[currentKey] ) group[currentKey] = [];

        var clone = duplicate(item);
        delete clone[key];        
        if( objlength(clone) ) group[currentKey].push( clone );

    }
    var returnGroup = [];
    for(var i in group){
        var groupItem = {};
        groupItem[config.keyName] = i;
        if( group[i].length ) groupItem[config.collectionName] = group[i];
        returnGroup.push( groupItem );
    }
    return returnGroup;
}


var result =  groupByLevel(data, ["country", "city", "employe"] );
var yourJson = JSON.stringify(result);

函数groupByLevel,groupBy,duplicate和objLength将处理您的灌浆。

在此链接http://jsfiddle.net/Castrolol/2TkkW/中,您可以看到包含数据的更高级别示例。

如果你愿意,你可以穿上单个物品进行分割并转为可重复使用。

抱歉我的英语不好。