ABOUT ME

알게 된 것을 기록하고, 그 기록을 나누어요.

Today
Yesterday
Total
  • [Javascript] 반복문으로 배열 만들고 안에 중복 없애기 (new Set)
    WEB Dev/Javascript | REACT | Node.js 2022. 6. 26. 13:59
    728x90

     

     

    카페24 카테고리를 만드려면 아래와 같은 ajax 코드를 사용해야 한다.

     

     

    /**
     * 카테고리 마우스 오버 이미지
     * 카테고리 서브 메뉴 출력
     */
    
    $(function(){
    
        var methods = {
            aCategory    : [],
            aSubCategory : {},
    
            get: function()
            {
                 $.ajax({
                    url : '/exec/front/Product/SubCategory',
                    dataType: 'json',
                    success: function(aData) {
    
                        if (aData == null || aData == 'undefined') return;
                        for (var i=0; i<aData.length; i++)
                        {
                            var sParentCateNo = aData[i].parent_cate_no;
    
                            if (!methods.aSubCategory[sParentCateNo]) {
                                methods.aSubCategory[sParentCateNo] = [];
                            }
    
                            methods.aSubCategory[sParentCateNo].push( aData[i] );
                        }
                    }
                });
            },
    
            getParam: function(sUrl, sKey) {
    
                var aUrl         = sUrl.split('?');
                var sQueryString = aUrl[1];
                var aParam       = {};
    
                if (sQueryString) {
                    var aFields = sQueryString.split("&");
                    var aField  = [];
                    for (var i=0; i<aFields.length; i++) {
                        aField = aFields[i].split('=');
                        aParam[aField[0]] = aField[1];
                    }
                }
                return sKey ? aParam[sKey] : aParam;
            },
    
            getParamSeo: function(sUrl) {
                var aUrl         = sUrl.split('/');
                return aUrl[3] ? aUrl[3] : null;
            },
    
            show: function(overNode, iCateNo) {
    
                if (methods.aSubCategory.hasOwnProperty(iCateNo) === false) {
                    return;
                }
    
                var aHtml = [];
                aHtml.push('<ul>');
                $(methods.aSubCategory[iCateNo]).each(function() {
                    aHtml.push('<li><a href="'+this.link_product_list+'">'+this.name+'</a></li>');
                });
                aHtml.push('</ul>');
    
    
                var offset = $(overNode).offset();
                $('<div class="sub-category"></div>')
                    .appendTo(overNode)
                    .html(aHtml.join(''))
                    .find('li').on({
                        mouseover: function(e) {
                            $(this).addClass('over');
                        },
                        mouseout: function(e) {
                            $(this).removeClass('over');
                        }
                    });
            },
    
            close: function() {
                $('.sub-category').remove();
            }
        };
    
        methods.get();
    
    
        $('.xans-layout-category li').on({
            mouseenter: function () {
                var $this = $(this).addClass('on'),
                    iCateNo = Number(methods.getParam($this.find('a').attr('href'), 'cate_no'));
    
                if (!iCateNo) {
                    iCateNo = Number(methods.getParamSeo($this.find('a').attr('href')));
                }
    
                if (!iCateNo) {
                    return;
                }
                methods.show($this, iCateNo);
            },
            mouseleave: function () {
                $(this).removeClass('on');
                methods.close();
            }
        });
    });

     

     

    위 코드를 가져다가 내가 필요한 정보만 받아오는 커스텀을 하려고 fetch를 이용해 데이터를 받아왔다.

    카테고리의 상단 카테고리들을 하나의 배열로 만드려고 하는데

    모든 카테고리가 다 불러와지다보니 반복문을 통해서 중복을 없앤 배열로 만들려고 한다.

     

    // 빈 배열 만들기
    let parentCategory = [];
    
    
     fetch(`/exec/front/Product/SubCategory`, {
        method: 'GET', // 또는 'PUT'
        headers: {
            'Content-Type': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
    },
    })
    .then((response) => response.json())
    .then((data) => {
        if (data === null || data === 'undefined') return false;
        data.forEach((element, i) => {
            let parentNo = element.parent_cate_no;
            ** productCate.push(parentNo);      
    });

     

    위의 코드에서 ** 로 만든 부분인데 

    이럴 때 쓸 수 있는 방법은 

     

    parentCategory를 에 데이터를 push 해주고 new Set()으로 중복을 정리해준 다음 배열로 변환해주면 된다.

    Set 은 중복을 허용하지 않는 자료구조이기 때문에 

     

     

    위와 같이 나타나는 중복 값이 많은 배열을 정리해줄 수 있다.

     

    위의 배열을 new Set에 넣어주고 -> new Set(Array);

    변수에 할당한 다음 -> const convertArray = new Set(Array);

    convertArray 를 다시 배열로 만들어주면 -> [...convertArray] (딥 카피 Deep copy)

    중복이 제거된다.

    나의 경우는 아래와 같이 줄였다.

     

    productCategory = [...new Set(productCategory)]

     

    위와 같이 해주고 콘솔을 찍어보면 

     

     

    아래와 같이 깔끔하게 중복이 제거된 배열을 얻어낼 수 있다.

    728x90

    댓글

Designed by Tistory.