코딩 기록/JavaScript
object 밖에 있는 object도 object의 값으로 가져오기 / object의 key값도 밖의 object에서 가져오기
NomadHaven
2023. 5. 17. 23:31
openinghours라는 object와 restaurnat라는 object가 각각 따로 존재한다고 가정하자.
const openingHours = {
thu: {
open: 12,
close: 22,
},
fri: {
open: 11,
close: 23,
},
sat: {
open: 0, // Open 24 hours
close: 24,
},
};
const restaurant = {
name: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto'],
order(starterIndex, mainIndex) {
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
},
orderDeliver({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
console.log(
`Order Received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be deliverd to ${address} at ${time}`
);
},
orderPasta(ing1, ing2, ing3) {
console.log(
`Here is your delicious pasta with ${ing1}, ${ing2} and ${ing3}`
);
},
만약 restaurant라는 object에서 openingHours의 value를 추가하고 싶다면 어떻게 할까?
무척 간단하다. 그냥 restaurnat object에서 openingHours의 object 이름만 입력하면 끝이다.
const restaurant = {
name: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto'],
//ES6 enhanced object literals
openingHours,
order(starterIndex, mainIndex) {
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
},
orderDeliver({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
console.log(
`Order Received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be deliverd to ${address} at ${time}`
);
},
orderPasta(ing1, ing2, ing3) {
console.log(
`Here is your delicious pasta with ${ing1}, ${ing2} and ${ing3}`
);
},
이와 같이 object안에 openingHours라는 속성만 추가한뒤 콘솔창에 restaurant object를 입력해보면
openingHours의 값이 잘 들어간게 확인 가능하다.
object의 이름만 적어도 값이 들어가게 된건 ES6이후 향상된 기능이라고 한다.
//ES6 전
orderPizza: function (mainIngredient, ...otherIngredients) {
console.log(mainIngredient);
console.log(otherIngredients);
}
//ES6 이후
orderPizza(mainIngredient, ...otherIngredients) {
console.log(mainIngredient);
console.log(otherIngredients);
}
ES6이후에는 object 안의 함수도 funtion까지 적을 필요 없이 이름만 적어도 사용 가능하게 변했다.
또한 object 의 key값 역시 object 외부에 있는 값에서 가져오기가 가능하다.
const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
const openingHours = {
[weekdays[3]]: {
open: 12,
close: 22,
},
[weekdays[4]]: {
open: 11,
close: 23,
},
[weekdays[5]]: {
open: 0, // Open 24 hours
close: 24,
},
};
openingHours 라는 object 안의 key값을 다른 곳에서 가져오고 싶다면,
위의 코드처럼 weekydays라는 배열에서 값을 가져오는 것도 가능하다.
위와 같이 코드를 구성하고 console창에 출력해도 배열에 있는 인덱스값과 일치하는 정확한 요일이 나온다.