如何使用默认参数来启动对象数组属性

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (20)

我正在尝试使用构造函数为类属性(一个对象)提供默认参数。其中是一个对象数组。我没有尝试任何作品

我想要最终得到的是对象的rowData属性是authData一个只有一个条目(一个对象)的数组。即authData

 {"catText": {"catName": "User Data", . . . },
 "rowData": [{
                 {"userName":'', "style":{ . . .}, 
                    . . . 
                 {"uID": "User ID", "style"{: . . . "width": 3}
            }]
 }

我试过的一种方法如下,Object.values().map(obj => [obj])但这不起作用。(简化的)代码(不编译... 'A parameter property is only allowed in a constructor implementation . . . A parameter initializer is only allowed in a function or constructor implementation' . . .)如下:

export interface AuthBlock {
    "catText": {"catName": string}
    "rowData": {
        "userName": {"Username": string,"style": {"type": string, "width": number}}, 
        "password":{"Password": string,"style": {"type": string, "width": number}}, 
        "uId":{"User ID": string,"style": {"type": string, "width": number}}
    }[]
}

export class AuthRow {

    constructor(
        public authData: AuthBlock = {
            "catText": {"catName": "User Data"},
            "rowData": Object.values({{
                "userName": {"Username": '',"style": {"type": "text", "width": 3}}, 
                "password":{"Password": '',"style": {"type": "password", "width": 5}}, 
                "uId":{"User ID": '',"style": {"type": "text", "width": 3}}
            }}).map(obj => [obj])
        }
    ){}
}

提问于
用户回答回答于
Object.keys(obj.rowData)
      .map(key => ({ [key]: obj.rowData[key] }))

获取对象上的键,使用map将其转换为数组,并将其转换为单独的对象。

编辑:

export interface AuthBlock {
    "catText": {"catName": string}
    "rowData": {
        "userName": {"Username": string,"style": {"type": string, "width": number}}, 
        "password":{"Password": string,"style": {"type": string, "width": number}}, 
        "uId":{"User ID": string,"style": {"type": string, "width": number}}
    }[]
}

export class AuthRow {

    constructor(
        public authData: AuthBlock = {
            "catText": {"catName": "User Data"},
            // Open array here
            "rowData": [{
                "userName": {"Username": '',"style": {"type": "text", "width": 3}}, 
                "password":{"Password": '',"style": {"type": "password", "width": 5}}, 
                "uId":{"User ID": '',"style": {"type": "text", "width": 3}}
            }]
            // Close here
        }
    ){}
}

扫码关注云+社区

领取腾讯云代金券