본문 바로가기

JS/JavaScript

10. JavaScript 객체, JSON

JavaScript 객체 

JavaScript 객체는 {} 내에 key : Value 가 모여있는 Map형태로 작성된다. -> { K:V, K:V, K:V...}

 

- JavaScript에서 객체를 생성하는 방법 

  1) {} : 객체 리터럴 표기법을 이용하여 생성 

  2) 생성자 + new 생성자()를 이용하여 생성 

 

** JS객체의 Key는 무조건 string(묵시적 string) = key 작성 시 "", '', 따옴표X 모두 string으로 인식

const brand = "Macdonald"

const product = {
    "pName" : "Cheese Burger",
    "brand" : "Burger King",
    price : 7000,
    size : ["s", "M", "L"],
    'info' : function(){
        console.log(brand)
    }
}

product.info(); 	
// 결과: Macdonald
// * 객체 내부의 함수에서 변수명을 작성하면 해당 객체 내의 변수(key)가 아닌, 전역변수가 선택된다. 
//  -> 이유: 같은 객체의 변수를 선택하는 방법이 별도로 존재 = 객체 내부에서 this 사용

//----------

const product = {
    "pName" : "Cheese Burger",
    "brand" : "Burger King",
    price : 7000,
    size : ["s", "M", "L"],
    'info' : function(){
        console.log(this.brand)
    }
}

product.info();  // 결과: Burger King

 

객체가 가지고 있는 값 출력하기 

1. 얻어오기

   - 객체명.key

   - 객체명['key']

console.log(product.pName)     // 결과: Cheese Burger
console.log(product.brand)     // 결과: Burger
console.log(product.price)     // 결과: 7000
console.log(product['size'])   // 결과: ['S', 'M', 'L']
console.log(product['info'])   // 결과: f(){console.log(this.brand)}

 

2. 대입하기 

  - 객체명.key = 값

  - 객체명['key'] = 값

product.price = 7500
console.log(product.price)  // 결과: 7500


product['Kcal'] = 750
console.log(product['Kcal') // 결과: 750 
// 객체에 없는 key에 값을 추가하면 객체에 추가된다.

 

3. 제거하기

  - delete 객체변수명.key

delete product.size
console.log(product)
// 결과
// {pName: 'Cheese Burger', brand: 'Burger King', price: 7500, Kcal: 750, info: ƒ}

 

4. for in문(객체 전용 for문) : 객체명 ['key'] 방법으로 객체가 가지고 있는 모든 값 출력 

   (형식) for(let key in 객체명){반복실행할 구문}

for(let key in product) {
    console.log(product[key])
}
// 결과
// Cheese Burger  Burger King  7500  ƒ(){console.log(this.brand)}  750
// 객체의 모든 key는 string으로 따옴표가 필요 없다.

  

 

생성자 함수

- 생성자 함수의 시작은 반드시 대문자

- JS함수의 매개변수는 let, const, var와 같은 키워드를 작성하지 않아도 됨 = 적지 않아도 함수의 지역변수로 취급 

- 생성자 함수에서의 this는 new 연산자를 통해 만들어지는 객체(앞으로 만들어질 객체) 

// 1. 생성자 함수 정의 
function Student(grade, name, major) {

    // 속성
    this.grade = grade
    this.name = name
    this.major = major

    // 기능
    this.introduce = function() {
        return `학년: ${this.grade} / 이름: ${this.name} / 전공: ${major}`
    }
}

document.getElementById("btn1").addEventListener("click", function(){
    const div1 =  document.getElementById("div1")
    const studentList = [];

    // 2. 생성자 함수 호출 : new 생성자함수명(매개변수) 
    studentList.push(new Student(2, "김강아지", "수학"))
    studentList.push(new Student(1, "박병아리", "체육"))
    studentList.push(new Student(3, "최송아지", "미술"))

    div1.innerHTML = "";

    // 3. 배열, 컬렉션 접근 for of
    // 현재 studentList: [{김강아지 정보} {박병아리 정보} {최송아지 정보}]
    // -> studentList 배열의 인덱스에 먼저 접근해야 함 
    for(let std of studentList){
        // console.log("std: " + std) 결과: [object object]

        // 배열 인덱스에 접근 후, 객체 key에 반복 접근하여 데이터 출력 
        for(let key in std) {
            // console.log("key: " + key) 결과: key : value

            // key의 자료형이 function이라면 실행 후 출력
            if(typeof std[key] == 'function') {
                div1.innerHTML += `${key}: ${std[key]()} <br>`
            } else {
                div1.innerHTML += `${key}: ${std[key]} <br>`
            }
        }
        div1.innerHTML += "<hr>"
    }
})

 

 


 

JSON(JavaScript Object Notation, 자바스크립트 객체 표기법) 

* JS객체: {"memberID":"user01", "memberPw":"pass01", "age":20}

  JSON문자열: '{"memberID":"user01", "memberPw":"pass01", "age":20}'

 

1) 간단한 포맷 

  : {괄호} 내에 "key":value 쌍으로 구성되어 있다. 

     - "key": 반드시 문자열 사용("" 필수) 

     -  value: string, value, boolean, array, object, null 데이터 저장 가능 

 

2) {객체} 또는 [배열]을 효율적으로 표시 가능 

3) 경량 데이터 교환 방식

4) 간단한 포맷을 가지고 있어 이해하기 쉬움

5) 순수 text 기반

   : 구조화된 text 형식으로 대부분의 프로그래밍 언어에서 JSON 포맷 데이터를 핸들링 할 수 있는 라이브러리를 제공하여 시스템 간의 객체 교환이 용이함

 

JavaScript JSON 내장객체 

JSON 포맷의 데이터를 간편하게 다룰 수 있도록 내장된 객체 

 

- JSON.stringify(JS객체) : JS객체를 JSON문자열로 변환

- JSON.parse(JSON문자열) : JSON문자열을 JS객체로 변환

const member = {"memberID":"user01", "memberPw":"pass01", "age":20}
console.log(JSON.stringify(member))
// JS객체 -> JSON 문자열 변환 

const member2 = '{"memberID":"user01", "memberPw":"pass01", "age":20}'
console.log(JSON.parse(member2))
// JSON 문자열 -> JS객체 변환

 

'JS > JavaScript' 카테고리의 다른 글

12. 함수  (0) 2023.03.04
11. DOM  (0) 2023.03.04
9. 윈도우 내장 객체  (0) 2023.03.02
8. 배열  (0) 2023.03.01
7. 형변환, 비교연산자, 문자열/숫자 내장함수  (0) 2023.03.01