JSON은 JavaScript Object Notation의 줄임말로, 데이터 교환을 위해 만들어진 객체 형태의 포맷
const message = {
sender: "김코딩",
receiver: "박해커",
message: "해커야 오늘 저녁 같이 먹을래?",
createdAt: "2021-01-12 10:10:10"
}
JSON.stringify : 객체를 JSON으로 변환 (직렬화)
JSON.parse : JSON을 객체로 변환 (역직렬화)
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`
function stringifyJSON(obj) {
if(typeof obj ==='boolean' || typeof obj ==='number' || obj === null) {
return String(obj);
}
if(typeof obj ==='string') {
return `"${obj}"`;
}
if(Array.isArray(obj)) { // 배열일때
let newArr = [];
for(let el of obj) {
newArr.push(stringifyJSON(el));
}
return `[${newArr}]`;
} else { // 객체일때
let result = ''
for(let key in obj) {
if(obj[key] === undefined || typeof obj[key] === "function"){
continue;
}
result = result + `${stringifyJSON(key)}:${stringifyJSON(obj[key])}`;
}
result = result.slice(0, -1);
return `{${result}}`;
}
};
function createTreeView(menu, currentNode) {
for (let i = 0; i < menu.length; i++) {
const li = document.createElement("li");
if (Object.keys(menu[i]).includes("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);
currentNode.append(li);
createTreeView(menu[i].children, ul);
} else {
li.textContent = menu[i].name;
currentNode.append(li);
}
}
}
재귀를 코드에 적용하니까 난이도가 확 올라가서 힘들었다.
내가 맞게 하고있는지 궁금해서 GPT한테 물어보고 과제를 진행함
DOM을 이용한 재귀는 아직도 이해가 되지않는다.😔