[TIL] Dictionary 키 할당, 분해하기

_sqrlkoo·2022년 7월 29일
0

항해 팀원들과 코드 리뷰 중 이해되지 않은 코드들이 있었다. 특별히 어려워 보이는 코드는 아니였지만 아예 이해가 가지 않았다.

알고보니 javascript 기초 문법이더라.. 그래서 오늘은 dictionary 키 할당, 분해하기 방법을 공부했다!

var city = 'seoul'
var population = 1000

city와 population값을 이용하여 딕셔너리를 만든다.

var aa = { city: city, population: population }
// city : "seoul", population : 1000

변수(또는 상수)에 값이 담겨있는데 키:값 입력하기 번거롭기 때문에 변수(또는 상수)명만 기입해도 된다.

변수(또는 상수)명이 키명이 되고 변수값이 키 값이 됩니다.

예를들면,

var bb = {city, population}
// city : "seoul", population : 1000

인덱스를 이용하여 bb딕셔너리 city값을 city_2에 저장하겠습니다.

var city_2 = bb['city']
// "seoul"

city_2에는 값이 잘 저장되었습니다.

* 키 분해하기

콤마를 이용해 여러 키들도 디스트럭쳐링 할 수 있습니다.

var cc = {city: 'busan', population: 500, latitude: 2, longitude: 3}

딕셔너리 cc에서 위도 경도만 뽑아보자

var {latitude, longitude} = cc
//latitude: 2, longitude:3

이때 디스트럭쳐링 할 변수(또는 상수)명의 앞뒤 순서는 상관없다!

* 다른이름으로 키 분해하기

디스트럭쳐링를 이용해서 bb 딕셔너리 city 값을 city_3에 저장해보겠습니다.

{ 분해할키:저장할이름 } 형태로 입력합니다.

var cc = {city: 'busan', population: 500, latitude: 2, longitude:3 }
var {city:city_3} = cc
//city_3: "busan"

* 키 기본값 지정하기

디스트럭쳐링할 때 값이 존재하지 않은 경우 기본값을 지정할 수 있습니다.

아래 부산에는 인구 500이 존재하므로 population 변수에 500이 할당되었습니다.

var cc = {city: 'busan', population: 500, latitude: 2, longitude:3 }
var { city, population=0 } = cc
console.log(city, population) // 결과: busan 500

아래 대구에는 인구정보가 없으므로 population 변수에 기본값인 0이 할당되었습니다.

var dd = {city: 'daegu' }
var { city, population=0 } = dd
console.log(city, population) // 결과: daegu 0

* 남은 키값 빼내기

디스트럭쳐링 후 남은 원소들을 ...(스프레드연산자)를 이용하여 빼낼 수 있습니다.

city를 디스트럭쳐링 하고 남은 키:값들을 others 로 빼냈습니다.

var cc = {city: 'busan', population: 500, latitude: 2, longitude:3 }
var { city, ...others } = cc
console.log(city)   // 결과: busan
console.log(others) // 결과: {population: 500, latitude: 2, longitude: 3}

참조

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=wideeyed&logNo=221818180319 >

0개의 댓글