let transferableMessage = JSON.stringify(message)
console.log(transferableMessage)
// `{"sender":"김코딩","receiver":"박해커","message":"해커야 오늘 저녁 같이 먹을래?","createdAt":"2021-01-12 10:10:10"}`
console.log(typeof(transferableMessage))
// `string`
let packet = `{"sender":"김코딩","receiver":"박해커","message":"해커야 오늘 저녁 같이 먹을래?","createdAt":"2021-01-12 10:10:10"}`
let obj = JSON.parse(packet)
console.log(obj)
/*
* {
* sender: "김코딩",
* receiver: "박해커",
* message: "해커야 오늘 저녁 같이 먹을래?",
* createdAt: "2021-01-12 10:10:10"
* }
*/
console.log(typeof(obj))
// `object`
자바스크립트 객체 | JSON | |
---|---|---|
키 | 키는 따옴표없이 쓸 수 있음 {key : "property' } | 반드시 큰따옴표를 붙여야함 '{"key":"property"}' |
문자열값 | 작은 따옴표도 사용 가능 { "key" : 'property' } | 반드시 큰따옴표로 감싸야 함 '{"key":"property"}' |
키와 값 사이 공백 | 사용 가능 {"key" : 'property'} | 사용 불가능 '{"key":"property"}' |
키-값 쌍 사이 공백 | 사용 가능 { "key":'property', num:1 } | 사용 불가능 '{"key":"property","num":1}' |
const array1 = ['a', 'b', 'c,];
array1.forEach(element => console.log(element));
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
const obj = {
name: 'curryyou',
job: 'engineer'
}
for (const key in obj){
console.log(`${key} : ${obj[key]}`);
}
// name : curryyou
// job : engineer
function stringifyJSON(obj) {
if(obj === null) {
return 'null';
}
if( typeof obj === 'boolean' || typeof obj === 'number') {
return `${obj}`;
}
if(typeof obj === 'string') {
return `"${obj}"`;
}
// obj가 배열인 경우
if(Array.isArray(obj)){
let result = [];
// forEach메서드 사용
obj.forEach((el)=>{
result.push(stringifyJSON(el));
})
//
return `[${result}]`;
}
// obj 객체인 경우
if(typeof obj === 'object'){
let result = "";
// for..in문 사용)
for(key in obj) {
// 객체안에 있는 키의 속성값이 빈배열이거나 함수일경우
if(obj[key] === undefined || typeof obj[key] === "function"){
// result = String(result)로 써도 됨;
// 현재 반복에서 명령문 실행 종료하고 다음 명령문 실행
continue;
// (,) 붙이고 마지막 배열에서는 빼줘야 함
} else {
result = result + `${stringifyJSON(key)}:${stringifyJSON(obj[key])},`;
}
}
// 마지막의 ,을 없애주기 위해 result.length-1을 사용
result = result.slice(0, result.length-1);
return `{${result}}`;
}
};
// 다음 코드는 결과 제출을 위한 코드입니다. 신경 쓰지 않아도 좋습니다.
if (typeof window === "undefined") {
module.exports = stringifyJSON;
}
function stringifyJSON(obj) {
// your code goes here
if (obj === null) {
return "null";
}
if (typeof obj === "number" || typeof obj === "boolean") {
return ${obj};
}
if (typeof obj === "string") {
return "${obj}";
}
if (Array.isArray(obj)) {
// 결과를 담을 빈배열 선언
const result = [];
// 배열을 순회하며 type체크
for (let i = 0; i < obj.length; i++) {
if (typeof obj[i] === "string") {
// 문자열인 경우 문자열형태로 result에 담기
result.push("${obj[i]}");
// 배열안에 배열일 경우 (재귀)
} else if (Array.isArray(obj[i])) {
result.push(stringifyJSON(obj[i]));
} else {
// obj가 문자열이 아니고, 배열이 아닐경우 (재귀탈출조건)
result.push(stringifyJSON(obj[i]));
}
}
return [${result}];
}
// for문쓰기 싫을경우 배열메서드 map가능
// 여기서는 따로 문자열 조건이 필요없는 이유가 stringifyJSON 함수 재귀를 돌며
// string 조건에 자동으로 걸리기때문
// if (Array.isArray(obj)) {
// const elements = obj.map((element) => stringifyJSON(element));
// return [${elements}];
// }
if (typeof obj === "object") {
const result = [];
// 객체의 key순회
for (let key in obj) {
// 값부분에 객체 혹은 배열이 들어가기때문에, value에 재귀가 필요함
const value = stringifyJSON(obj[key]);
// key의 값이 있는경우 (undefined 예외조건 처리)
if (value !== undefined) {
result.push("${key}":${value});
}
}
return {${result}};
}
}
const input = document.createElement('input')
input.setAttribute('type', 'checkbox') // = input.type = 'checkbox';
// index.html의 id가 root인 ul태그를 읽어옴
const root = document.getElementById('root');
// currentNode는 root를 동적인 요소(dom)으로 만든 내용?이 들어감
function createTreeView(menu, currentNode) {
for(let i = 0; i < menu.length; i++) {
// li 요소 생성 (li은 자식요소 유/무 둘다에도 있으니 먼저 생성)
const li = document.createElement('li')
// menu에 'children'없으면 check,span,ul없이 li만 있음 (Base)
if(!menu[i].children) {
li.textContent = menu[i].name; //li에는 메뉴 이름만 넣어주기
currentNode.append(li); //currentNode에 li 넣어주기
}
// menu에 'children'있으면 checkbox,span,ul,li (recursive)
else {
const input = document.createElement('input')
// input.type = 'checkbox';
input.setAttribute('type', 'checkbox') // input태그에 'checkbox'속성주기
const span = document.createElement('span')
span.textContent = menu[i].name; // span태그에 메뉴 이름 넣기
const ul = document.createElement('ul')
// li 태그에 input, span, ul태그 넣기
li.append(input, span, ul)
currentNode.append(li);
// 재귀함수 사용해서 자식요소에 자식요소가 있는지 확인해주기
createTreeView(menu[i].children, ul);
}
}
}
// DOM 생성이 완료된 뒤에 함수 실행
createTreeView(menu, root);