삼류야수
5
2017-05-08 14:12:34.0
4
358

for문이 계속 반복되는데 줄일수없나요.


조직도 차트 그리는거 보고 소스하드코딩으로 써봤는데 for문이 depth길이 만큼 계속반복되는데 

depth길이에 따라 자동으로 for문이 반복되게 할수있을까요?

대충 소스는 이런식인데요.

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

datasource['children'].push({'name': depth1[i]['GROUPNAME'], 'gid': depth1[i]['GROUP_ID'],'children':[]});

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

if(depth1[i]['GROUP_ID'] == depth2[j]['GROUP_ID_P']){

datasource['children'][i]['children'].push({'name': depth2[j]['GROUPNAME'], 'gid': depth2[j]['GROUP_ID'], 'children':[]});

for(var k=0; k<depth3.length; k++){

if(depth2[j]['GROUP_ID'] == depth3[k]['GROUP_ID_P']){

for(var l=0; l<datasource['children'][i]['children'].length; l++){

if(depth2[j]['GROUP_ID'] == datasource['children'][i]['children'][l]['gid']){

datasource['children'][i]['children'][l]['children'].push({'name': depth3[k]['GROUPNAME'], 'gid': depth3[k]['GROUP_ID'], 'children':[]});

for(var m=0; m<depth4.length; m++){

if(depth3[k]['GROUP_ID'] == depth4[m]['GROUP_ID_P']){

for(var n=0; n<datasource['children'][i]['children'][l]['children'].length; n++){

if(depth3[k]['GROUP_ID'] == datasource['children'][i]['children'][l]['children'][n]['gid']){

datasource['children'][i]['children'][l]['children'][n]['children'].push({'name': depth4[m]['GROUPNAME'], 'gid': depth4[m]['GROUP_ID'], 'children':[]});

}

}

}

}

}

}

}

}

}

}

}

0
0
  • 답변 4

  • pokemon
    195
    2017-05-08 14:21:47.0

    depth1~9999까지 object 안으로 밀어 넣어버리고


    object.length 만큼 for 돌리면 간결해질것 같은 저의 의견 이 였습니다.



    0
  • 20523
    1k
    2017-05-08 15:00:45.0

    저는 머리가 좋지 않아서, 자료구조가 머리에 한번에 그려지지는 않습니다만.


    이럴 때 사용하라고 만들어 둔 개념이 recursive function 아닐까요?

    0
  • 20523
    1k
    2017-05-08 16:22:49.0

    머리가 안 좋아서, 1시간 20분 걸렸는데, .. 참고만 하세요.

    잘 아시는 분들이 잘못된 부분을 교정해 주시면 좋은데..

    var depth1 = [];
    var depth2 = [];
    var depth3 = [];
    var depth4 = [];
    
    depth1.push(
        {
            GROUP_ID: 1,
            GROUPNAME: '본사',
    	children: []
        },
        {
            GROUP_ID: 2,
            GROUPNAME: '지사',
    	children: []
        }
    );
    
    depth2.push(
        {
            GROUP_ID: 10,
            GROUP_ID_P: 1,
            GROUPNAME: '기술지원본부',
    	children: []
        },
        {
            GROUP_ID: 20,
            GROUP_ID_P: 1,
            GROUPNAME: '연구소',
    	children: []
        },
        {
            GROUP_ID: 30,
            GROUP_ID_P: 2,
            GROUPNAME: '영업부',
    	children: []
        }
    );
    
    console.log(depth1);
    console.log("========================================");
    console.log(depth2);
    console.log("========================================");
    
    /*
    var datasource = { children: [] };
    
    for(var i=0; i<depth1.length; i++){
    	datasource['children'].push({'name': depth1[i]['GROUPNAME'], 'gid': depth1[i]['GROUP_ID'],'children': []});
    	for(var j=0; j<depth2.length; j++){
    		if(depth1[i]['GROUP_ID'] == depth2[j]['GROUP_ID_P']){
    			datasource['children'][i]['children'].push({'name': depth2[j]['GROUPNAME'], 'gid': depth2[j]['GROUP_ID'], 'children':[]});
    			for(var k=0; k<depth3.length; k++){
    				if(depth2[j]['GROUP_ID'] == depth3[k]['GROUP_ID_P']){
    					for(var l=0; l<datasource['children'][i]['children'].length; l++){
    						if(depth2[j]['GROUP_ID'] == datasource['children'][i]['children'][l]['gid']){
    							datasource['children'][i]['children'][l]['children'].push({'name': depth3[k]['GROUPNAME'], 'gid': depth3[k]['GROUP_ID'], 'children':[]});
    							for(var m=0; m<depth4.length; m++){
    								if(depth3[k]['GROUP_ID'] == depth4[m]['GROUP_ID_P']){
    									for(var n=0; n<datasource['children'][i]['children'][l]['children'].length; n++){
    										if(depth3[k]['GROUP_ID'] == datasource['children'][i]['children'][l]['children'][n]['gid']){
    											datasource['children'][i]['children'][l]['children'][n]['children'].push({'name': depth4[m]['GROUPNAME'], 'gid': depth4[m]['GROUP_ID'], 'children':[]});
    										}
    									}
    								}
    							}
    						}
    					}
    				}
    			}
    		}
    	}
    }
    
    console.log("===== FINAL =====");
    console.log(JSON.stringify(datasource));
    */
    
    /**
     * tree에서 gid를 가지는 객체를 반환한다.
     * 못 찾으면 undefined를 반환한다.
     */
    function findById(tree, gid) {
    
    	//console.log("========================================");
    	//console.log(new Error().stack);
    	//console.log("========================================");
    
    	if ( tree['GROUP_ID'] == gid ) {
    		return tree;
    	} else if ( tree.children.length == 0 ) {
    		return undefined;
    	} else {
    		for ( var i = 0 ; i < tree.children.length ; i ++ ) {
    			var found = findById(tree.children[i], gid);
    			if ( found !== undefined ) {
    				return found;
    			}
    		}
    		return undefined;
    	}
    }
    
    var ROOT = {
    	'GROUP_ID': 0,
    	'GROUPNAME': 'ROOT',
    	'children': []
    }
    
    depth1 = depth1.concat(depth2);
    for ( var i = 0 ; i < depth1.length ; i ++ ) {
    	if ( depth1[i]['GROUP_ID_P'] === undefined ) {
    		ROOT.children.push(depth1[i]);
    	} else {
    		var parent = findById(ROOT, depth1[i]['GROUP_ID_P']);
    		if ( parent !== undefined ) {
    			parent.children.push(depth1[i]);
    		}
    	}
    }
    
    console.log("FINAL");
    
    console.log(JSON.stringify(ROOT));


    1
  • 삼류야수
    5
    2017-05-08 16:27:36.0

    감사합니다. 어설프게나마 감이오네요 ㅎㅎㅎ

    0
  • 로그인을 하시면 답변을 등록할 수 있습니다.