❗️참고) 객체는 length의 프로퍼티를 가지고 있지 않습니다.
❗️참고) '속성(property)'이라는 용어는 키-값 쌍을 의미합니다.
1️⃣ Bracket notaton
객체이름["속성이름"]
const user = {
firstname: "John",
lastname: "Doe"
};
user["firstName"]; // "John"
user["lastname"]; // "Doe"
//❗️참고) Dot notaton보다 활용도가 좋다.
2️⃣ Dot notaton
객체이름.속명이름
const user = {
firstname: "John",
lastname: "Doe"
};
user.firstName; // "John"
user.lastname; // "Doe"
const user = {
firstname: 'John',
lastname: 'Doe',
city: 'Seoul'
}
const town = 'city'
user['city'] // 'Seoul'
user[town] // 'Seoul'
user['city'] === user[town] //true
user['city'] === user[city] // Error 발생.
// user[city]는 틀린 문법이다.
한마디로 말하면 문자열과 변수의 차이이다.
user[city]에 city는 문자열이 아닌 변수인데,
city라는 변수가 선언된 적이 없기에 Error가 발생한다.
객체이름["추가할속성이름"] = "추가할값"
객체이름.추가할속성이름 = "추가할값"
const user = {
firstname: 'John',
lastname: 'Doe',
city: 'Seoul'
}
user['age'] = '28'
user.email = 'tata@email.com'
// bracket/dot notation을 이용한 값 추가
delete
const user = {
firstname: 'John',
lastname: 'Doe',
city: 'Seoul'
}
delete user['city'];
delete user.city;
// city의 키-값 쌍을 지운다.
// {firstname: 'John', lastname: 'Doe'}
1️⃣ for in 문
const obj = {
firstname: 'John',
lastname: 'Doe',
city: 'Seoul'
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(obj[key]);
}
}
// John, Doe, Seoul 출력
// 'hasOwnProperty'는 확장 또는 외부의 값을 쓰지 않게 하는 언어이다.
2️⃣ for of 문
const obj = {
firstname: 'John',
lastname: 'Doe',
city: 'Seoul'
}
for (const key of obj) {
console.log(key);
}
// John, Doe, Seoul 출력
❗️참고)
객체 { } 에서 for in은 index 값, 배열 [ ] 에서 for in은 배열 값이다.
객체 { } 에서 for of는 사용을 잘 안하고, 배열 [ ] 에서 for of는 배열 값을 꺼내온다.
Object.keys()
객체의 키를 배열로 나열해 준다.
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
Object.values()
객체의 value 값을 배열로 나열해 준다.
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]
Object.entries()
[key, value] 쌍의 배열을 반환한다.
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
Object.fromEntries()
{key, value} 쌍의 객체를 반환한다.
const entries = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }
Object.assign()
대상 객체에 붙여넣는다.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget === target);
// expected output: true
빈 객체에 붙여넣기도 가능하다.
const source = { a: 1, b: 4, c: 5 };
const newSource = Object.assign({}, source);
console.log(newSource);
// expected output: Object { a: 1, b: 4, c: 5 }
Object.is()
같은 주소의 객체를 가리키면 true, 아니라면 false를 반환한다.
const target = { a: 1, b: 2 };
const source = { a: 1, b: 2 };
console.log(Object.is(target, target));
// expected output: true
console.log(Object.is(target, source));
// expected output: false
'속성이름' in 객체이름
프로퍼티가 있으면 true, 없으면 false를 반환한다.
let coffee = {latte: 3, vanilla: 4, mocha: 1 };
'latte' in coffee // true
'americano' in coffee // false
let myPlants = [
{
type: "flowers",
list: ["rose", "Mugunghwa", "sunflower"],
},
{
type: "trees",
list: ["pine", "maple", "ginkgo"],
},
];
myPlants[1].list[1] // maple
// "maple"은 배열 myPlants의 [1]번 째 인덱스에 할당된 객체에
// list라는 프로퍼티의 [1]번 째 value이다.
myplants[1]["type"] // trees
// "trees"은 배열 myPlants의 [1]번 째 인덱스에 할당된 객체에
// type이라는 프로퍼티의 value이다.
더 쉬운 예제
let arr = [{ name: "jin"}, { name: "suga" }, { name: "jimin" }]
arr[1]["name"] // suga
arr[2]["name"] //jimin
arr[0].name // jin
let storageCar = "car";
let storageOutside = "outside";
let storageTrunk = "trunk";
let myStorage = {
car: {
inside: {
"glove box": "maps",
"passenger seat": "crumbs",
},
outside: {
trunk: "jack",
},
},
};
// 점 표기법
console.log(myStorage.car.outside.trunk)
//jack
// 대괄호 표기법 1. 문자열로 접근
console.log(myStorage['car']['outside']['trunk']
//jack
// 대괄호 표기법 2. 변수로 접근
console.log(myStorage[storageCar][storageOutside][storageTrunk]
//jack