티스토리 뷰

Tip 10. 객체를 이용해 정적인 키-값을 탐색하라

 

* 객체는 변화가 없고 구조화된 키-값 데이터를 다루는 경우에 유용하다.

* 자주 갱신되거나 실행되기 전에는 알 수 없는 동적인 정보를 다루기에는 객체가 적합하지 않다.

ex) 색상 컬렉션을 공유하는 경우 객체를 선택한다. 데이터가 변경될 가능성이 없기 때문이다.

const colors = {
    red: '#d10202',
    green: '#19d836',
    blue: '#0e33d8'
}

 

=> colors.red로 직접 참조하여 사용 가능하고 정적인 정보에 적합하고 반복/갱신/대체/정렬되는 정보는 맵이 적절하다.

 

export const config = {
  endpoint: 'http://pragprog.com',
  key: 'secretkey',
};
//  # END:config

//  # START:between
function getBill(item) {
  return {
    name: item.name,
    due: twoWeeksFromNow(),
    total: calculateTotal(item.price),
  };
}

const bill = getBill({ name: '객실 청소', price: 30 });

function displayBill(bill) {
  return `${bill.name} 비용은 ${bill.total} 달러이며 납부일은 ${bill.due}입니다.`;
}

=> 함수 내에서 객체를 생성하고 다른 함수에 넘겨줄 수도 있다.

=> 기존 객체를 조작하는 것이 아닌 각각의 함수에서 새로운 객체를 생성하고 다른 함수에 넘겨준다.

=> 키의 값으로 함수를 호출할 수 있도록 할 수 있다.

 

Tip 11. Object.assign()으로 조작 없이 객체를 생성하라

* 조작하지 않고 객체를 갱신할 수 있다.

collections/assign/problem.js

const original = {
  author: '',
  title: '',
  year: 2017,
  rating: null,
};
//  # START:add
const defaults = {
  author: '',
  title: '',
  year: 2017,
  rating: null,
};

const book = {
  author: 'Joe Morgan',
  title: 'Simplifying JavaScript',
};

function addBookDefaults(book, defaults) {
  const fields = Object.keys(defaults);
  const updated = {};
  for (let i = 0; i < fields.length; i++) {
    const field = fields[i];
    updated[field] = book[field] || defaults[field];
  }
  return updated;
}

=> for문 이후 key-value 형태를 반환하는 updated 객체

=> 논리합 연산자 비교를 통해 먼저 왼쪽 key를 반환하고, 뒤이어 중복되지 않은 남은 key들을 반환한다.

 

Object.assign(defaults, book);

// {
//   author: 'Joe Morgan',
//   title: 'Simplifying JavaScript',
//   year: 2017,
//   rating: null,
// }

=> assign은 일련의 객체를 전달받고 가장 먼저 인수로 받은 객체(defaults)를 뒤이어 인수로 넘긴 객체(book)의 키-값을 이용해 갱신.

=> 갱신된 첫 번째 객체 반환, 먼저 전달한 객체부터 적용(author, title) 그리고 나중에 전달한 객체 마지막 적용(year, rating)

 

 

Tip 12. 객체 펼침 연산자로 정보를 갱신하라

function updateBookYear() {
//  # START:year
  const book = {
    title: 'Reasons and Persons',
    author: 'Derek Parfit',
  };

  const update = { ...book, year: 1984 };

  // { title: 'Reasons and Persons', author: 'Derek Parfit', year: 1984}
  //  # END:year
  return update;
}

function updateBookTitle() {
//  # START:title
  const book = {
    title: 'Reasons and Persons',
    author: 'Derek Parfit',
  };

  const update = { ...book, title: 'Reasons & Persons' };

  // { title: 'Reasons & Persons', author: 'Derek Parfit' }
  //  # END:title
  return update;
}

=> 새로운 정보는 펼침 연산자의 앞이나 뒤에 쉽게 추가할 수 있다.

=> 펼침 연산자는 동일한 키에 서로 다른 값을 추가하면 어떤 값이든 가장 마지막에 선언된 값을 사용한다.

 

const defaultEmployee = {
  name: {
    first: '',
    last: '',
  },
  years: 0,
};

const employee = Object.assign({}, defaultEmployee);

const employee2 = Object.assign(
  {},
  defaultEmployee,
  {
    name: Object.assign({}, defaultEmployee.name),
  },
);

const employee = {
    ...defaultEmployee,
    name: {
      ...defaultEmployee.name,
    },
  };

=> 중첩된 객체가 있는 경우 객체를 복사하지 않고 참조만 복사하므로 조작으로 인한 문제 발생 가능성 있음.

=> 객체 펼침 연산자를 사용하여 새로운 객체를 생성하려는 의도를 명확하게 알 수 있다.

'JS' 카테고리의 다른 글

Angular 폴더구조  (1) 2024.10.21
Next.js  (3) 2024.10.18
2장 배열로 데이터 컬렉션을 관리하라 (Tip7-9)  (2) 2023.10.29
2장 배열로 데이터 컬렉션을 관리하라  (2) 2023.10.28
1장 변수 할당으로 의도를 표현하라  (0) 2023.10.21
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함