Javascript

큐를 활용하여 데이터 자료구조 변경하기

Antonio Bae 2023. 7. 21. 14:13

안녕하세요 오늘은 객체, 배열로 이루어진 짬뽕의 데이터가 들어왔을때,

상사가 보기 힘들어 하겠죠. 

이를 구분하고 하나하나 파싱하여 원하는 구조로 다시 만드는 형태입니다.

 

예를 들면 데이터가 이렇게 들어왔습니다.

originList = [
{ "아이유" : { "자바스크립트" : 88, "파이썬" : 99 } },
{ "제드" : { "자바스크립트" : 90, "파이썬" : 88 } }
];

 

이를 이렇게 자료구조를 변경하라고 할때 어떻게 해야 할까요?

[
{ "자바스크립트": [ [ 1, "조대룡", 88 ], [ 2, "자드", 90 ] ] },
{ "파이썬": [ [ 1, "조대룡", 99 ], [ 2, "자드", 88 ] ] }
]

 

다음과 같이 여러가지 학습 방법들을 익히고 나서, 각각 파싱을 해본 후, 큐에 데이터를 넣고 뽑아내면 됩니다.

말은 쉽죠^^ 저도 이 객체,배열,큐 에서 일주일 정도를 학습한 것 같습니다.

연습1. 배열 합치기 연습

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>배열 합치기</title>
</head>
<body>
<script>
let myV1 = [3,4,5];
let myV2 = ["no1","no2","no3"];

let myV3 = {[myV2[0]] : myV1[0],[myV2[1]]:myV1[1], [myV2[2]]:myV1[2]};
console.log(myV3);

let myV4 = { [myV2[0]] : myV1[0] }; // 키 이름의 객체로 사용할때 중괄호 사용
//대괄호는 주로 list와 관련됐을 때, 중괄호는 적용 대상이나 실행 대상 등 대상을 적을 때, 소괄호는 특정 조건을 명시할 때 사용
console.log(myV4);

let myId = "AAA";
let myIDN = 12345;
let myA = []
let myV5 = {[myId]: myV1[0]};
//변수인 경우에는 중괄호를 사용해야 함
for(let i=0; i<10; i++) {
myA.push( {[myId+myIDN+i]:"ZZZ"});
}
console.log("i"+myV5);
console.log(myA);

let myB = {}
for(i=0; i<myV1.length; i++){
myB[myV2[i]] = myV1[i];
}
console.log(myB);

let myC = {}
for(i=0; i<myV1.length; i++){
myC = {...myC, [myV2[i]]: myV1[i]}
}
console.log(myC);

let obj1 = {"no1":1, "no2":2, "no3":3 }
//["no1","no2","no3"]
//[1,2,3]

for(let key in obj1){
document.write(key+"<br>");
document.write(obj1[key]+"<br>");// value값은 객체의 중괄호를 씌운 i값
}


</script>
 
</body>
</html>

연습2. 큐에 넣고 나래비 세워보기

let myObj = {"no1":1, "no2":2, "no3":3 }
       let myObj1 = {"no1":"cdr", "no2":"zard", "no3":"love" }

다음과 같은 객체들이 있다고 할때, 큐 클래스를 만들어 데이터를 넣고 뽑아내는 방법입니다.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>☆☆ 큐 클래스를 만들어 데이터를 넣고 뽑아내는 방법☆☆☆</title>
</head>
<body>
<script>
document.write("console찍어봐야해요");
class myQQ {
constructor(idV) {
this.idV = idV;
this.queueArray = [];
} // idV는 식별자
pushItem(inItem) {
this.queueArray.push(inItem);
}
shiftItem() {
return this.queueArray.shift();
}
get getsize() {
return this.queueArray.length;
} //length잡는거
}


let myObj = {"no1":1, "no2":2, "no3":3 }
let myObj1 = {"no1":"cdr", "no2":"zard", "no3":"love" }
//myA1 =["no1","no2","no3"]
//myA2 =[1,2,3]
//{"cdr":"no1",}

let q1 = new myQQ(1);
let q2 = new myQQ(2);
let q3 = new myQQ(3);
let q4 = {};

for(let keyName in myObj){
q1.pushItem(keyName);
q2.pushItem(myObj[keyName]);
}

console.log(q1);
console.log(q2);
document.write(q3);

for(let keyName in myObj1){
q3.pushItem(myObj1[keyName]+":"+keyName);
}
console.log(q3);

for(; q1.getsize >0; ){
q4 = {...q4, [q2.shiftItem()] : q1.shiftItem()}
}
console.log(q4);


</script>
</body>
</html>

연습 3. 배열 큐에 넣고 객체 형태로 뽑아내기

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>배열 큐에 넣고 객체 형태로 뽑아내기</title>
</head>

<body>
<script>
//map함수는 callbackFunction을 실행한 결과를 가지고 새로운 배열을 만들 때 사용
let name = ["ZARD", "CDR", "LOVE"];
let number = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
// {ZARD: [1,2,3,4]}
// {CDR: [5,6,7,8]}
// {LOVE: [9,10,11,12]}

class myQ {
constructor(idV) {
this.idV = idV;
this.queueArray = [];
}
pushItem(inputV) {
this.queueArray.push(inputV);
}
shiftItem() {
return this.queueArray.shift();
}
get getSize() {
return this.queueArray.length;
} //length잡는거
}
let q1 = new myQ(1);
let q2 = new myQ(2);
let q3 = new myQ(3);
let q4 = {};
let myObj = { [name]: number }; //name이 갖고 있는 값들을 갖고 오고싶을때 중괄호 활용
console.log(myObj);

let myObj2 = { name: number };
console.log(myObj2);

let specialQueue = new myQ(1);

for (let i = 0; i < name.length; i++) {
specialQueue.pushItem({ [name[i]]: number[i] });
}
document.write(specialQueue);
//안되는 사람들은 배열고차함수 복습할것!!
let tempQueue = new myQ(2);
// {ZARD: [[1],[2],[3],[4]]}
// {CDR: [[5],[6],[7],[8]]}
// {LOVE: [[9],[10],[11],[12]]}
for (let i = 0; i < name.length; i++) {
// tempQueue.push(number[i]); //[1,2,3,4]
specialQueue.pushItem({ [name[i]]: number[i].map((v, i, a) => [v]) });
}
console.log(specialQueue);

//. map 함수는 filter함수와 같이 Object(객체)타입도 컨트롤 할 수도 있다.
var students = [
{ id: 5, name: "james" },
{ id: 6, name: "tim" },
{ id: 7, name: "john" },
{ id: 8, name: "brian" }
];

var names = students.map(student => student.name);
console.log(names);




</script>
</body>

</html>

 

 

최종보스!!

데이터 자료구조 변경하기 코드입니다.

<!DOCTYPE html>
<html lang="ko">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>성적데이터 업데이트하기</title>
</head>

<body>
<script>
/*
originList = [
{ "조대룡" : { "자바스크립트" : 88, "파이썬" : 99 } },
{ "자드" : { "자바스크립트" : 90, "파이썬" : 88 } }
];
===========================>
1.다음과 같은 형태로 뽑기 배열안에 객체 형태로 과목: [index, 이름, 점수]
[
{ "자바스크립트": [ [ 1, "조대룡", 88 ], [ 2, "자드", 90 ] ] },
{ "파이썬": [ [ 1, "조대룡", 99 ], [ 2, "자드", 88 ] ] }
]
*/
let obj1 = { "CDR": [1004], "ZARD": [1005], "LOVE": [1006] }
// ["CDR","ZARD","LOVE"]
// [1004,1005,1006]
let strArr = Object.values(obj1);// 변수의 값 출력
document.write(strArr + "<br>");
let index1 = obj1[0]
//배열의 첫번째값 출력
// document.write(index1+"<br>");

jumsuList = [
{ "조대룡": { "자바스크립트": 88, "파이썬": 99 } },
{ "자드": { "자바스크립트": 90, "파이썬": 88 } },
{ "러브": { "자바스크립트": 100, "파이썬": 50 } }
];

//배열의 첫번째 값 출력
// let indexFirst = [jumsuList[0]];
// document.write(indexFirst);

//배열 첫번째 값 출력
console.log(jumsuList[0]);
//조대룡(키값) 출력
document.write(Object.keys(jumsuList));
//자바스크립트 출력
console.log(Object.values(jumsuList[0]));

let myObj = { [jumsuList]: jumsuList[0] }; //name이 갖고 있는 값들을 갖고 오고싶을때 중괄호 활용
console.log(myObj);

class QueueClass {
constructor() {
this.qArray = [];
}
unshiftItem(inV) {
this.qArray.unshift(inV);
}
popItem() {
this.qArray.pop();
}
get getReturnArray() {
return this.qArray;
}
enqueue(element) {
this.qArray.push(element);
}
dequeue() {
if (this.isEmpty()) {
return null;
}
return this.qArray.shift();
}
isEmpty() {
return this.qArray.length === 0;
}
}
const queue = new QueueClass();
// const queue2 = new QueueClass();
// const queue3 = new QueueClass();

// Enqueue data into the queue
jumsuList.forEach((item, index) => {
Object.entries(item).forEach(([name, scores]) => {
Object.entries(scores).forEach(([subject, score]) => {
queue.enqueue([subject, index + 1, name, score]);
});
});
});

const result = [];
const subjects = {};

// Dequeue data and construct the final result
while (!queue.isEmpty()) {
const [subject, index, name, score] = queue.dequeue();
if (!subjects[subject]) {
subjects[subject] = [];
}
subjects[subject].push([index, name, score]);
}

// Convert subjects object to the desired output format
Object.keys(subjects).forEach(subject => {
const newObj = { [subject]: subjects[subject] };
result.push(newObj);
});

console.log(result);
</script>
</body>

</html>