angular - วิธีการเพิ่มอาร์เรย์ string[] เข้าไปในรูปแบบ record โดยใช้ typescript?
ฉันมีอาเรย์ของสตริงและฉันต้องการเก็บค่าพวกนั้นไว้และสร้างอาเรย์ใหม่ชื่อ Record
สำหรับค่าทุกค่าที่อยู่ใน userValue
ตัวอย่าง
userValue: string[] = ["1111","2222","3333","4444"];
selectedOptions: Record<string, boolean> = {
//how to add userValue array into here?
1111: true, //hardcoded
2222: true, //hardcoded
3333: true, //hardcoded
4444: true //hardcoded
};
คำตอบ #1
// Create the array of strings
let userValue: string[] = ["1111","2222","3333","4444"];
// Create empty Record
let selectedOptions: Record<string, boolean> = {} as Record<string, boolean>;
// Add the array values into the Record
userValue.forEach(val => {
selectedOptions[val] = true;
});
