[230816] JS Destructuring Assignment
JS Destructuring Assignment
- 구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JS 표현식
- 객체나 배열을 쉽게 추출하거나 병합 가능
- ES6 문법
객체 분해를 사용하여 객체 속성을 추출
const person = { firstName: "John", lastName: "Doe", age: 30 };
const { firstName, lastName } = person;
console.log(firstName); // 'John'
console.log(lastName); // 'Doe'
배열 구조 분해
const foo = ["one", "two", "three"];
const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
나머지 구문을 이용해서 분해 가능
const [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
매개변수 기본 값 설정
function drawES2015Chart({
size = "big",
cords = { x: 0, y: 0 },
radius = 25,
} = {}) {
console.log(size, cords, radius);
// 차트 그리기 수행
}
drawES2015Chart({
cords: { x: 18, y: 30 },
radius: 30,
});
매개변수로 전달된 객체에서 해체하기
function userId({ id }) {
return id;
}
function whois({ displayName: displayName, fullName: { firstName: name } }) {
console.log(displayName + " is " + name);
}
const user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe",
},
};
console.log("userId: " + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"
객체 구조 분해에서 Rest
const { a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 };
a; // 10
b; // 20
rest; // { c: 30, d: 40 }
직접 회사에서 편하게 쓴 방식
export interface DashboardOverviewTableProps {
total: number[];
male: number[];
female: number[];
}
export function DashboardOverviewTable({
total,
male,
female,
}: DashboardOverviewTableProps) {}
//사용
<DashboardOverviewTable {...stats} />;
- 서버에서 받은 객체와 props로 받을 객체와 키 값이 같아서 바로 사용하면 편함
Leave a comment