JSON 객체의 데이터를 filter 적용하기

Progmming/Javascript|2023. 3. 24. 18:49
반응형

json 데이터를 filter 적용하는 예제

 

const jsonData = [
  { "숙소코드": 123, "숙소명": "호텔A", "사용여부": "Y" },
  { "숙소코드": 456, "숙소명": "모텔B", "사용여부": "N" },
  { "숙소코드": 789, "숙소명": "게스트하우스C", "사용여부": "Y" }
];

const filteredData = jsonData.filter(data => data["사용여부"] === "Y");

console.log(filteredData);

 

 

댓글()

한글 포함 문자열 바이트로 자르기 substring

Progmming/Javascript|2021. 12. 23. 11:23
반응형
       function getTextLength(str) {
           var len = 0;
           for (var i = 0; i < str.length; i++) {
               if (escape(str.charAt(i)).length == 6) {
                   len++;
               }

               len++;
           }

           return len;
       }

       function cutStr(str, start, size) {
           var i = 0;
           var lim = 0;
           var pos = 0;
           var beg = 0;
           var minus = 0;
           var len = getTextLength(str);

           for (var i = 0; pos < start; i++) {
               pos += (str.charCodeAt(i) > 128) ? 2 : 1;
           }

           beg = i;


           for (i = beg; i < len; i++) {
               lim += (str.charCodeAt(i) > 128) ? 2 : 1;

               if (lim > size) {
                   break;
               }
           }

           return str.substring(beg, i);
       }

 

댓글()

javascript Table 로 Excel 파일 생성 다운받기

Progmming/Javascript|2021. 7. 29. 15:49
반응형

table id 를 지정해서

 

해당 테이블을 엑셀 파일로 생성시켜주는 함수.

 

테이블 아이디 , 파일명 ,  시트명을 변수처리함.

 

    var makeToExcel = (function () { 
        var style = "<style> td,th {width:100px;} </style>";
        var uri = 'data:application/vnd.ms-excel;base64,'
            , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->' + style + '<meta http-equiv="Content-Type" content="application/vnd.ms-excel; charset=utf-8"/></head><body><table border="1">{table}</table></body></html>'
            , base64 = function (s) {
                return window.btoa(unescape(encodeURIComponent(s)))
            }
            , format = function (s, c) {
                return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; })
            }
        return function (table, fileName , sheetName) {
            if (!table.nodeType) table = document.getElementById(table)
            var ctx = { worksheet: sheetName || 'Worksheet', table: table.innerHTML }
			console.log(table.innerHTML); 
            let a = document.createElement('a');
        a.href = uri + base64(format(template, ctx));
        a.download = fileName+'.xls';
        a.click();
        }
    })()
	
	makeToExcel('테이블아이디', '파일명' ,'시트명');

댓글()

Javascript 배열 정렬하는 방법 sort()

Progmming/Javascript|2018. 12. 17. 14:13
반응형

Javascript 배열 정렬 샘플 코드 



기본 사용법 


Sorting ascending // 오름차순 정렬

<script>
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
for(i=0;i<points.length;i++)
{
	document.write(points[i]+",");
}
</script>


 Sorting descending // 내림차순 청렬

<script>
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});

for(i=0;i<points.length;i++)
{
	document.write(points[i]+",");
}
</script>



적용 샘플

<!doctype html> <html lang="en"> <head> <script src="//code.jquery.com/jquery-1.7.2.js"></script> </head> <body> <h1>DIV sorting</h1> <input type="button" value="Add" id="btnAdd" /> <div id="starting_divs"> <div class="item" data-order="100"> <table> <tr> <td>STD</td> <td>100</td> </tr> </table> </div> <div class="item" data-order="50"> <table> <tr> <td>STD</td> <td>50</td> </tr> </table> </div> <div class="item" data-order="500"> <table> <tr> <td>STD</td> <td>500</td> </tr> </table> </div> <div class="item" data-order="150"> <table> <tr> <td>STD</td> <td>150</td> </tr> </table> </div> </div> <script type="text/javascript"> function fnSort() { var $sorted_items, getSorted = function(selector, attrName) {                          return $( $(selector).toArray().sort(function(a, b){ var aVal = parseInt(a.getAttribute(attrName)), bVal = parseInt(b.getAttribute(attrName)); return aVal - bVal; }) ); }; $sorted_items = getSorted('#starting_divs .item', 'data-order').clone(); $('#starting_divs').html( $sorted_items ); } $("#btnAdd").on("click",function(){ var order = (Math.random()*10000).toString().substring(0,3); $("<div class=\"item\" data-order=\""+order+"\"> \ <table><tr><td>DLX</td><td>"+order+"</td></tr></table> \ </div>").insertAfter(".item:last"); fnSort(); }); </script> </body> </html>


데이터형에 따라서 문자열일 경우 비교/리턴 하는부분에서 아래와 같이 변경한다.

<script>
return $(
	$(selector).toArray().sort(function(a, b){
		var aVal = a.getAttribute('sort-name'), bVal = b.getAttribute('sort-name');
		return aVal.localeCompare(bVal);
	})
</script>


복합 정렬일 경우 아래와 같이 || 조건으로 비교한다.

<script> return $( $(selector).toArray().sort(function(a, b){ var aint = parseInt(a.getAttribute('sort-int')), bint = parseInt(b.getAttribute('sort-int')), aName = a.getAttribute('sort-name'), bName = b.getAttribute('sort-name'); return aint - bint || aName.localeCompare(bName); }) ); </script>


w3schools Link : https://www.w3schools.com/js/js_array_sort.asp



최종 사용하려고 했던 함수.

<script type="text/javascript">

	function fnSort(sortBy)
	{
 
		$(".btn.btn-white").removeClass("active");

		var $sorted_items,
			getSorted = function(selector) {
				switch(sortBy){
					case "AVAILABLE" :
						$(".btn.btn-white").eq(1).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aStatus = a.getAttribute('sort-status'),
								bStatus = b.getAttribute('sort-status'),
								aPrice = parseInt(a.getAttribute('sort-price')),
								bPrice = parseInt(b.getAttribute('sort-price')),
								aName = a.getAttribute('sort-name'),
								bName = b.getAttribute('sort-name');
								return aStatus.localeCompare(bStatus) || aPrice - bPrice || aName.localeCompare(bName);
							})
						);
						break;
					case "PRICE" :
					case "LOWPRICE" :
						$(".btn.btn-white").eq(2).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aPrice = parseInt(a.getAttribute('sort-price')),
								bPrice = parseInt(b.getAttribute('sort-price')),
								aName = a.getAttribute('sort-name'),
								bName = b.getAttribute('sort-name');
								return aPrice - bPrice || aName.localeCompare(bName);
							})
						);
						break;
					case "HIGHPRICE" :
						$(".btn.btn-white").eq(3).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aPrice = parseInt(a.getAttribute('sort-price')),
								bPrice = parseInt(b.getAttribute('sort-price')),
								aName = a.getAttribute('sort-name'),
								bName = b.getAttribute('sort-name');
								return bPrice - aPrice || aName.localeCompare(bName);
							})
						);
						break;
					case "RATING" :
					case "GRADE" :
						$(".btn.btn-white").eq(4).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aGrade = parseInt(a.getAttribute('sort-grade')),
								bGrade = parseInt(b.getAttribute('sort-grade')),
								aName = a.getAttribute('sort-name'),
								bName = b.getAttribute('sort-name');
								return aGrade - bGrade || aName.localeCompare(bName);
							})
						);
						break;
					case "HENM" :
						$(".btn.btn-white").eq(5).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aVal = a.getAttribute('sort-name'), bVal = b.getAttribute('sort-name');
								return aVal.localeCompare(bVal);
							})
						);
						break;
					default :
						$(".btn.btn-white").eq(5).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aVal = a.getAttribute('sort-name'), bVal = b.getAttribute('sort-name');
								return aVal.localeCompare(bVal);
							})
						);
						break;
				}
			};

		$sorted_items = getSorted('#starting_divs .item').clone();

		$('#starting_divs').html( $sorted_items );
 
	}
</script>


댓글()