본문 바로가기
Frontend/Javascript

[Javascript] 자바스크립트 Dictionary 사용하기

by YERIEL_염주둥 2022. 3. 23.
728x90

Javascrpt에서 객체를 사용하다보면  키,값으로 된 dict를 자주 사용하게 됩니다.

하지만 MDN이 제공하고 있는 문서에 보면 dict이나 Dictionary는 찾아 볼 수 없는데 딕셔너리라는 표현은 파이썬에서 사용하는 용어이기 때문입니다. MDN Document에서 Dicionary에 관한 부분을 보고 싶다면 Object를 찾아야해요.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects

 

표준 내장 객체 - JavaScript | MDN

이 장은 JavaScript의 모든 표준 내장 객체와 그 메서드 및 속성을 나열합니다.

developer.mozilla.org

 


Object든 Dictionary든 사용하다보면 Arrary와 문법이 헷갈릴때가 많죠...ㅋㅋㅋ 그래서 정리해보려고 합니다.

// object 초기값 없이 선언
var obj = {}
// object 초기값 있어 선언
var obj2 = {id:1, git:'YERIEL-RYU', instagram: 'r_0o0_j'}
// object 프로퍼티 접근
var git = obj2['git']
var git2 = obj2.git
// object 프로퍼티 추가
obj2['tistory'] = 'r-0o0-j.tistory.com'
console.log(obj2) // 콘솔 결과 {id: 1, git: 'YERIEL-RYU', instagram: 'r_0o0_j', tistory: 'r-0o0-j.tistory.com'}
// object key 값 가져오기
var key = Object.keys(obj2)
console.log(key) // ['id', 'git', 'instagram', 'tistory']
// object value 값 가져오기
var value = Object.values(obj2)
console.log(value) // [1, 'YERIEL-RYU', 'r_0o0_j', 'r-0o0-j.tistory.com']
// object key, value 가져오기
var entries = Object.entries(obj2)
console.log(entries) // [['id', 1], ['git', 'YERIEL-RYU'], ['instagram', 'r_0o0_j'], ['tistory', 'r-0o0-j.tistory.com']]
// array to object
const arr = [
['foo', 'bar'],
['baz', 42]
]
const arrToObject = Object.fromEntries(arr)
console.log(arrToObject) // { foo: "bar", baz: 42 }
view raw object.js hosted with ❤ by GitHub
반응형