개발자 첫걸음/The WEb Developer BootCamp 2022

Section 18: JavaScript 객체 리터럴(Literals)

프로아마추어 2022. 4. 23. 00:47

 

1. 객체 리터럴 (Object Literals)개요

Object

  • Objects are collections of properties
  • Properties are a key-value pair
  • Rather than accessing data using an index, we use custom key

객체란?

  • 순서가 중요하지 않은 레이블에 이름을 정해 저장하는 것
  • key와 value이라는 한쌍의 속성을 가지고 있다.
객체이름 = {
	key: value,
}

 

2. 객체 리터럴 생성하기

리터럴이란?

  • JavaScript에서 객체는 다양한 의미를 담고 있다.
  • 여기서 이야기하고자 하는 객체는 중괄호를 사용하여 key, value를 가지고 있는 데이터 구조를 말한다.

첫 객체 리터럴 만들기

// 빈 객체 생성
const empty = {}

const person = {
 name: 'Kevin', // 한쌍의 property는 쉼표로 구분한다.
 age: 27, // 배열과 같이 다양한 타입의 값들을 담을 수 있다.
 height: 182,
 weight: 75,
 favoriteColor: ['gray', 'black'],
 isGraduate: false,
}

 

3. 객체 외부 데이터에 액세스하기

객체 value 가져오기

const person = {
 name: 'Kevin', 
 age: 27,
 height: 182,
 weight: 75,
 favoriteColor: ['gray', 'black'],
 isGraduate: false,
}

// 괄호 표기법
person['name']; // 'Kevin'

// 존재하지 않는 key를 사용하면 undefined값이 나온다.
person['firstName']; // undefined 

// 점 표기법
person.age; // 27

// 객체의 key값이 숫자로 보이지만 기호를 제외한 key는 전부 문자열로 변환된다.
const years = {1992: 'awesome', 2020: 'too bad'}

years['1992']; // 'awesome'
years['2020']; // 'too bad'

const smth = {true: 'adsf', null: 'qwer'};

smth['true']; // 'adsf'
smth['null']; // 'qwer'

person.name; // 'Kevin'
person['name']; // 'Kevin'

// 대괄호 안쪽에 명시된 key 값은 따옴표로 감싸주어야 한다.
person[name]; // 에러 발생

person['na' + 'me']; // 'Kevin'

// 괄호 표기법에서는 변수를 key값으로 사용할 수 있다.
let birthyear = 2020;
years[birthyear]; // 'too bad'

// 점 표기법에서 변수를 key값으로 사용하면 years 객체의 key로 
// birthyear을 사용하고 있지 않으므로 value값을 찾지 못한다.
years.birthyear; // undefined

 

4. 객체 수정하기

객채의 정보를 추가하거나 수정해봅시다.

const scores = {lee: 100, kim: 77}
scores // {lee: 100, kim: 77}

// const 객체를 선언했음에도 배열과 같이 메모리 주소 값을 참조하므로
// 객체 내부의 값을 handling할 수 있다.
scores.lee = 20; // 20
scores.lee = 60; // 60

scores // {lee: 60, kim: 77}

scores.lee = 'D';
scores['kim'] = 'C+';

scores // {lee: 'D', kim: 'C+'}

// 객체 property 추가
scores.park = 'A-';
scores.kang = 'A';

scores // lee: 'D', kim: 'C+', park: 'A-', kang: 'A'}

 

5. 배열과 객체 네스트 구성하기

  • 배열과 객체에는 어떠한 타입의 변수도 담을 수 있다.
  • 배열 + 객체의 구조도 가능하다.
// 배열의 요소가 객체인 데이터 구조
const shoppingCart = [
	{
		product: 'Jenga Classic,
		price: 12000,
		quantity: 1,
	},
	{
		product: 'Echo Dot,
		price: 36000,
		quantity: 3,
	},
	{
		product: 'Fire Stick,
		price: 42000,
		quantity: 2,
	}
]

// 객체의 value값이 배열인 경우
const student = {
	firstName: 'David',
	lastName: 'Jones',
	strengths: ['Music', 'Art'],
	exams: {
		midterm: 92,
		final: 88
	}
}