首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用默认参数初始化对象数组属性

如何使用默认参数初始化对象数组属性
EN

Stack Overflow用户
提问于 2019-04-01 02:05:53
回答 1查看 95关注 0票数 0

我正在尝试使用构造函数为class属性提供默认参数,它是一个对象。。。其内部是一个对象数组。我试过的都不管用。。。

我想要结束的是让authData对象的rowData属性成为一个只有一个条目的数组(一个对象)。。。即authData

代码语言:javascript
复制
 {"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' . . .)的详细信息如下:

代码语言:javascript
复制
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])
        }
    ){}
}

如果您有任何想法,请提前表示感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-01 02:22:20

代码语言:javascript
复制
Object.keys(obj.rowData)
      .map(key => ({ [key]: obj.rowData[key] }))

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

编辑:

代码语言:javascript
复制
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
        }
    ){}
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55443879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档