객체(Object)는 key 값과 value값이 쌍으로 이루어져있다.
객체를 생성하고 객체의 값에 접근해보자.
let pesron = { name: '제임스', bloodType: 'B형', favorite: 'coffee' }
{ }중괄호를 사용해서 객체를 생성하고, key와 value를 쌍으로 묶어서 만들어 준다. key값이 여러 개라면 ,쉼표로 구분한다.(Object Literal)
Dot Notation
let box = { "hat": "ballcap", "shirt": "jersey", "shoes": "cleats" } console.log(box.shoes); //"cleats"
Bracket Notation
let box = { "hat": "ballcap", "shirt": "jersey", "shoes": "cleats" } console.log(box["hat"]); //"ballcap"
변수로 접근
let box = { "hat": "ballcap", "shirt": "jersey", "shoes": "cleats" } let cap = "hat"; console.log(box[cap]); //"ballcap"
객체안에 위치하고 있는 객체에 접근해보자.
tvBrand의 값이 "samsung"이 되게 해보자.
let myHouse = { "home": { "livingroom": { "tv": "samsung", "audio": "harman" }, "bedroom": { "bed": "simons" } } }; let tvBrand = myHouse.home.livingroom["tv"]; //객체안의 객체의 값에 접근하는 모습 console.log(tvBrand); //"samsung"
객체안에 위치하고 있는 배열에 접근해보자.
pineFound의 값이 "pine"이 되게 해보자.
let myPlants = [ { type: "flowers", list: [ "rose", "tulip", "dandelion" ] }, { type: "trees", list: [ "fir", "pine", "birch" ] } ]; let pineFound = myPlants[1].list[1]; //myPlants의 인덱스가 1인 배열에 접근한 후, list의 1번 인덱스에 접근. console.log(pineFound); //"pine"
위의 3), 4)의 객체 접근은 . 마침표 연산자를 사용했지만 []대괄호 연산자를 사용해도 접근이 가능하다. 또, []대괄호 연산자를 사용했을 경우 key 값이 띄어쓰기가 포함되어도 사용이 가능하다.
let box = { "hat": "ballcap", "shirt": "jersey", "shoes": "cleats" } box.hat = "벙거지 모자"; console.log(box); /*{ hat: "벙거지 모자", shirt: "jersey", shoes: "cleats" }*/
box에 "ring"프로퍼티를 추가하고, "ring"프로퍼티는 "gold"라는 값을 값게 해주자.
let box = { "hat": "ballcap", "shirt": "jersey", "shoes": "cleats" } box.ring = "gold"; console.log(box); /* { hat: "ballcap", ring: "gold", shirt: "jersey", shoes: "cleats" } */
let box = { "hat": "ballcap", "shirt": "jersey", "shoes": "cleats", "ring": "gold" } delete box.ring; console.log(box); /* { hat: "ballcap", shirt: "jersey", shoes: "cleats" } */