昨天學習了物件取值有兩種 點記號 與 中括號 取值方式
如果今天的資料是 id 、 name ,可能可以這樣寫
const id = user.id;
const name = user.name;
但假設我們有以下屬性需要提取:id, name, username, email, address, phone, website, company, street, suite, city, zipcode, geo.
const id = user.id;
const name = user.name;
const username = user.username;
const email = user.email;
const address = user.address;
const phone = user.phone;
const website = user.website;
const company = user.company;
const street = user.address.street;
const suite = user.address.suite;
const city = user.address.city;
const zipcode = user.address.zipcode;
const geo = user.address.geo;
const {
id,
name,
username,
email,
address,
phone,
website,
company,
address: { street, suite, city, zipcode, geo }
} = user;
這樣的解構賦值方式大大簡化了提取多個屬性的過程,同時也使得代碼更加清晰和易讀。
另外,我覺得解構方式,滿常看到其他人程式碼跟其餘參數做搭配使用,假設API來的資料物件中不需要提取那麼多屬性時,就可以用
{users.map(user => {
const { id, name, username, email, ...rest } = user;
console.log('剩餘的資料:', rest);
return <UserCard key={id} id={id} name={name} username={username} email={email} />;
})}