Crowdpleasr
Crowdpleasr

Reputation: 4044

How to use default parameters to initiate an array of objects property

I'm trying to use the constructor to provide default parameters for a class property, which is an object . . . inside of which is an array of objects. Nothing I try works . . .

What I want to end up with is having the rowData property of the authData object be an array with one just entry (an object). . . i.e. authData:

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

One approach I tried is below, with Object.values().map(obj => [obj]) but this isn't working. The (simplified) code (which doesn't compile . .. 'A parameter property is only allowed in a constructor implementation . . . A parameter initializer is only allowed in a function or constructor implementation' . . .) is below:

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])
        }
    ){}
}

Many thanks in advance if any ideas!

Upvotes: 0

Views: 111

Answers (1)

Rachael Dawn
Rachael Dawn

Reputation: 889

Object.keys(obj.rowData)
      .map(key => ({ [key]: obj.rowData[key] }))

Get the keys on the object, use map to convert it to an array, and transform it into separate objects.

EDIT:

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
        }
    ){}
}

Upvotes: 1

Related Questions