I would like to refill the array of TypeScript.

Asked 2 years ago, Updated 2 years ago, 254 views

I am making a screen with Angular.In a component of a screen,

class Sub{
    constructor(
        aaa —string,
        bbb —string,
        ccc:string
    ) {}
}

Import the above class and get a response from the API for this type so that it can be used for row selection in the table

typeExtendSub=Sub&{
    isSelected: boolean;
}


// returned response
const response: Sub[] = [
    { aaa: "a", bbb: "b", ccc: "c"},
    { aaa: "a", bbb: "b", ccc: "c"},
    { aaa: "a", bbb: "b", ccc: "c"},
]

I'd like to add this as below.

 constex:ExtendSub[] = [
    { aaa: "a", bbb: "b", ccc: "c", isSelected: false},
    { aaa: "a", bbb: "b", ccc: "c", isSelected: false},
    { aaa: "a", bbb: "b", ccc: "c", isSelected: false},
]

I don't know how to convert it.I would appreciate it if you could let me know if there is any other solution.

typescript angular

2022-11-12 16:58

1 Answers

Using the map function, you can write:

typeSub={
    aaa:string;
    bbb:string;
    ccc:string;
}

typeExtendSub=Sub&{
    isSelected: boolean;
}

const response: Sub[] = [
    { aaa: "a", bbb: "b", ccc: "c"},
    { aaa: "a", bbb: "b", ccc: "c"},
    { aaa: "a", bbb: "b", ccc: "c"},
]

constex=response.map<ExtendSub>(item=>{
    return {...item, isSelected:false}
});

console.log(ex); // Expected value

Playground


2022-11-12 18:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.