객체를 전송하기 위한 조건
- 수신자와 발신자가 같은 프로그램을 사용한다.
- 문자열처럼 범용적으로 읽을 수 있어야 한다.
객체를 전송하기 위해서 우리는 객체를 문자열로 변환시켜야 하는데 객체를 그냥 String()
메서드로 변환시킬 경우 [object Object]
와 같은 결과를 보여준다. 이를 해결해 주기 위한 메서드는 아래와 같다.
JSON.stringify
(직렬화) : 객체를 JSON으로 변환한다.JSON.parse
(역직렬화) : JSON을 객체로 변환한다.
JS 객체 | JSON | |
---|---|---|
키 | 키는 따옴표 없이 쓸 수 있음{ key : "property" } | 반드시 큰따옴표를 붙여야 함 '{"key":"property"}' |
문자열 값 | 작은 따옴표도 사용 가능 { "key" : 'property' } | 반드시 큰따옴표로 감싸야 함 '{"key":"property"}' |
키와 값 사이 공백 | 사용 가능 {"key" : 'property'} | 사용 불가능 '{"key":"property"}' |
키-값 쌍 사이 공백 | 사용 가능 { "key":'property', num:1 } | 사용 불가능 '{"key":"property","num":1}' |
function stringifyJSON(obj) { if(Array.isArray(obj)){ let arr = []; for(let i = 0; i < obj.length; i++){ arr.push(stringifyJSON(obj[i])) } return `[${arr}]`; } if(typeof(obj) !== 'object' || obj === null){ if(typeof(obj) === 'string'){ return `"${obj}"` } if(typeof(obj) === 'undefined'){ return ''; } return String(obj); } if(typeof(obj) === 'object'){ let newObj = "" for (let key in obj) { let objKey = stringifyJSON(key) let objVal = stringifyJSON(obj[key]) newObj += `${objKey}:${objVal},` if (!objVal) { newObj = "" } } return `{${newObj.slice(0, newObj.length - 1)}}` } return obj; };
재귀함수를 이용한 트리구조 UI 구현하기
const root = document.getElementById('root'); function createTreeView(menu, currentNode) { for(let i = 0; i < menu.length; i++){ const li = document.createElement('li'); if(menu[i].children){ const input = document.createElement('input'); input.type = 'checkbox' const span = document.createElement('span'); span.textContent = menu[i].name const ul = document.createElement('ul'); li.append(input, span, ul) createTreeView(menu[i].children, ul) } else { li.textContent = menu[i].name; } currentNode.append(li) } } createTreeView(menu, root);