[JS] looping arrays and objects, optional chaining(?.)

Hyodduru ·2021년 12월 9일
0

JavaScript

목록 보기
34/60
post-thumbnail

강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)

Section 9 - Data Structures, Modern Operators and Strings

참고 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: openingHours 라고 안적어도 됌.
  openingHours,

  //좀더간단한 function 형태. 굳이 order = function(){} 이렇게 적어줄 필요 없음.
  order(starterIndex, mainIndex) {
    return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
  },

  orderDelivery({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
    console.log(
      `Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`
    );
  },

  orderPasta(ing1, ing2, ing3) {
    console.log(
      `Here is your delicious past with ${ing1}, ${ing2} and ${ing3}`
    );
  },
  orderPizza(mainIngredient, ...otherIngredient) {
    console.log(mainIngredient);
    console.log(otherIngredient);
  },
};

Looping Arrays : The for-of Loop

const menu = [...restaurant.starterMenu, ...restaurant.mainMenu];

for (const item of menu) {
  console.log(item);
}
//to get item's index
for (const [i, el] of menu.entries()) {
  console.log(`${i + 1} : ${el}`);
} //1 : Focaccia
//  2 : Bruschetta
//  3 : Garlic Bread
//  4 : Caprese Salad
//  5 : Pizza
//  6 : Pasta
//  7 : Risott
console.log(...menu.entries());

Enhanced Object Literals

1. property name 과 valuable name 이 같을 경우 한번만 적어주면 된다!
2. 객체 내의 function은 function 생략 가능!
3. compute properties name
ex)

const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];

const openingHours = {
  [weekdays[3]]: {
    open: 12,
    close: 22,
  },
  [weekdays[4]]: {
    open: 11,
    close: 23,
  },
  //ES6 - compute properties name (value값 뿐만아니라 properties name도 가능해짐!) ex)[`day-${2 + 4}`]

  [weekdays[5]]: {
    open: 0, // Open 24 hours
    close: 24,
  },
}; 
//ES6 enhanced object literals openingHours: openingHours 라고 안적어도 됌.
const restaurant = {
		openingHours,
//좀 더 간단한 function 형태. 굳이 order = function(){} 이렇게 적어줄 필요 없음.
order(starterIndex, mainIndex) {
    return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
  }}      

Optional Chaining(?.)

optional chaining(?.)에서 '?'의 의미는 optional을 뜻한다. nullish 여부를 알고싶은 property 뒤에 ?를 붙히면 된다!

참고) optional chaining과 nullish coalescing operator는 nullish value 에 따라 계산한다는 점!

Short Circuiting

if (restaurant.openingHours && restaurant.openingHours.mon)
  console.log(restaurant.openingHours.mon.open);

WITH optional chaining

console.log(restaurant.openingHours.mon?.open);
console.log(restaurant.openingHours?.mon?.open);

Example

const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
for (const day of days) {
  const open = restaurant.openingHours[day]?.open ?? 'closed'; 
  console.log(`On ${day}, we open at ${open}`);
}

주의) restaurant.openingHours.day 라고 할 수 없음! day is not an actual property name of the object. variable name을 property name으로 쓰고 싶다면 "brackets notation []"을 써줘야한다는 점 기억하기!

Looping Objects : Object Keys, Values, and Entries

Properties NAMES

const properties = Object.keys(openingHours);
console.log(properties);

let openStr = `We are open on ${properties.length}days.: `;
for (const day of properties) {
  //console.log(day); //thu fri sat
  openStr += `${day},`;
}
console.log(openStr); //We are open on 3days.: thu,fri,sat, 참고) 이 콘솔을 for 내에 적을 경우 각각의 day마다 다 입력됌. 3번 입력됌.

Property VALUES

const values = Object.values(openingHours);

Entire object

const entries = Object.entries(openingHours);

// [key, value]  get key and value by destructuring
console.log(entries);
for (const [key, { open, close }] of entries) {
  console.log(`On a ${key} we open at ${open} and close at ${close}`);
}

Methods

console.log(restaurant.order?.(0, 1) ?? 'Method does not exist'); //(2) ['Focaccia', 'Pasta']
console.log(restaurant.orderRisotto?.(0, 1) ?? 'Method does not exist'); //Method does not exist

Arrays

const users = [{ name: 'Jonas', email: 'hello@jonas.io' }];
console.log(users[0]?.name ?? 'User array empty'); //Jonas
profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글