let 객체명 = {
프로퍼티명1(key) : 값1(value),
프로퍼티명2(key) : 값2(value)
...
}
값(value) 가져오기
객체.key객체['key']객체.key()객체 내의 key값 유무에 따라 프로퍼티를 추가하거나 수정할 수 있다.
let user = {
name : {
firstName : 'steve',
lasgName : 'Lee'
},
age : 20,
hello() {
console.log(`hello ${this.name.firstName}`)
}
}
user.gender = '남' // 추가
user.gender = '여' // 수정
콘솔에 user를 입력하면 해당 객체에 프로퍼티가 추가된 걸 확인할 수 있다.
delete 객체명.key
'key' in 객체명 : 존재여부에 따라 true / false 출력한다.'gender' in user // true
'age' in user // false
let obj = {
a: 2,
b: 'hello',
c: false
}
Object.keys(객체이름) : 주어진 객체의 속성명(key)들을 배열로 반환한다.console.log(Object.keys(obj))
// [a, b, c]
Object.values(객체이름) : 주어진 객체의 값(value)들을 배열로 반환한다.console.log(Object.values(obj))
// [2, 'hello', false]
let obj = {a: 1, b: 2}
let obj2 = {b: '일', c: '이'}
Object.assign(타겟객체, 합칠객체) : 타켓객체에 합칠객체가 더해진 후, 타겟객체가 반환된다.let assignObj = Object.assign(obj, obj2)
console.log(obj) // {a: 1, b: '일', c: '이'}
console.log(obj === assignObj) // true
obj와 assignObj는 같은 주소에 저장된 객체이므로 한쪽의 값이 변경되면 다른 한 쪽도 변경된다.
obj.a = '일'
console.log(obj) // {a: '일', b: '일', c: '이'}
console.log(assignObj) // {a: '일', b: '일', c: '이'}
Object.assign({}, 객체이름) : 객체가 깊은 복사된다.let newObj = Object.assign({}, obj)
console.log(newObj) // {a: '일', b: '일', c: '이'}
console.log(obj === newObj) // false
Object.is(객체1, 객체2)Object.is(obj, newObj) // false
Object.is(obj, assignObj) // true
객체의 key에 접근하여 반복작업
let obj = {
a: 2,
b: 'hello',
c: false
}
for(key in obj) {
console.log(`${key} : ${obj[key]}`);
}
/*
a : 2
b : hello
c : false
*/