แปลงคุณสมบัติเฉพาะจาก Record เป็น Array ใน Typescript/Javascript
ต้องแปลงชนิด Record ใน Typescript/Javascript เป็น Array ที่มีคุณสมบัติเฉพาะ
const store: Record<ProductID, ProductObject> = {
'france': productObject:{
present: 'in_stock',
amount: 23,
},
'uk': productObject:{
present: 'in_stock',
amount: 20,
},
'japan': productObject:{
present: 'no_stock',
amount: 0,
},
}
ผลลัพธ์: กำลังสร้างอาร์เรย์ใหม่ เพิ่มคีย์ใหม่เป็น 'country' และนำเฉพาะคุณสมบัติ 'amount' จากประเภทบันทึกในสตอร์
const newArrayFromRecord = [
{country: 'france', amount: 23},
{country: 'uk', amount: 20}
{country: 'japan', amount: 0}
]
ฉันได้ลองใช้ Object.entries() แล้วค่อยนำไปใส่ใน Array แต่ทั้งหมดต้องใช้โค้ดที่ไม่จำเป็น มีวิธีที่มีประสิทธิภาพกว่านี้ไหม..
คำตอบ #1
นี่คือวิธีหนึ่งที่เป็นไปได้ในการบรรลุเป้าหมาย:
Object.entries(store).map(([k, v]) => ({
country: k,
amount: v.amount
}))
โค้ดตัวอย่างโดยใช้ JS:
const store = {
'france': {
present: 'in_stock',
amount: 23,
},
'uk': {
present: 'in_stock',
amount: 20,
},
'japan': {
present: 'no_stock',
amount: 0,
},
};
console.log(
'result: ',
Object.entries(store).map(([k, v]) => ({
country: k,
amount: v.amount
}))
);และนี่คือลิงก์ไปยัง TypeScript Playground
คำตอบ #2
คุณสามารถวนลูปผ่านอ็อบเจ็กต์ store โดยใช้ลูป for in ได้
หรือการแมปมันด้วย Object.keys
นอกจากนั้นฉันไม่คิดว่าจริง ๆ แล้วจะมีวิธีแก้ปัญหาที่ 'มีประสิทธิภาพ' มากกว่า
const store = {
france: {
present: "in_stock",
amount: 23,
},
uk: {
present: "in_stock",
amount: 20,
},
japan: {
present: "no_stock",
amount: 0,
},
};
const result = [];
for (const country in store) {
result.push({ country, amount: store[country].amount });
}
const result_2 = Object.keys(store).map((country) => ({
country,
amount: store[country].amount,
}));
console.log(result);
console.log(result_2);