如何使用TypeScript将一个string[]数组添加到record<string,boolean>格式中?

4

我有一个字符串数组,想要保留这些值并创建一个新的数组 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
  };

使用JavaScript的map()函数:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map - C.M.
1个回答

6
// 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;
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接