Develop

자바스크립트 | 정렬, 객체 배열 합치기

HongUniverse 2023. 2. 23. 18:19
반응형

사이트맵을 만드는 과정에서 제목을 클릭했을 때 하위 제목들이 나올 수 있도록 구현하였다.

var data = {
    
    name : "최상위제목",

    parentdDatas : [
        {
            title : '부모제목 1',
            childDatas : [
                {
                    title : '자식제목 1_1',
                    position : 1,
                    content : '테'
                }, 
                {
                    title : '자식제목 1_2',
                    position : 2,
                    content : '스'
                }
            ]
        }, 
         {
            title : '부모제목 2',
            childDatas : [
                {
                    title : '자식제목 2_1',
                    position : 2,
                    content :'중'
                }, 
                {
                    title : '자식제목 2_2',
                    position : 1,
                    content :'트'
                }
            ]
        } 
    ]
};

let li = [...data.parentdDatas];
let obj = {};
//title을 키 값으로 자식 데이터를 묶어주는 작업
for(let tmp of li){
    //position에 맞게 정렬하는 작업 
    tmp.childDatas.sort((a, b) => parseInt(a.position) - parseInt(b.position));
    obj[tmp.title] = tmp.childDatas;
}

//제목을 클릭 시 하위 리스트를 가져올 수 있는 기능 
function selectTitle(title){
    let currentTitle = title;
    let currentContentList = obj[currentTitle];

    for(let content of currentContentList){
        console.log(content.content);
    }
}

//'테스트중' 출력
selectTitle('부모제목 1');
selectTitle('부모제목 2');
반응형