So, I have two classes
Item { name: string; desc: string; meta: string} ViewItem { name: string; desc: string; hidden: boolean; }
I have an array of Item that needs to be converted into an array of ViewItem. Currently, I am looping through the array using for, instantiating ViewItem, assigning values to attributes and pushing it to the second array.
Is there a simple way to achieve this using lambda expressions? (similar to C#) Or is there any other means?
The Typescript generally it converts one data type to another data type by using the cast operation. We can convert all types of datas are converted from one type to another type like that cast object is one of the features for to convert the object type of values to another type.
Use the concat function, like so: var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA. concat(arrayB); The value of newArray will be [1, 2, 3, 4] ( arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).
You haven't showed enough of your code, so I'm not sure how you instantiate your classes, but in any case you can use the array map function:
class Item { name: string; desc: string; meta: string } class ViewItem { name: string; desc: string; hidden: boolean; constructor(item: Item) { this.name = item.name; this.desc = item.desc; this.hidden = false; } } let arr1: Item[]; let arr2 = arr1.map(item => new ViewItem(item));
(code in playground)
This can be shorter with Object.assign
:
constructor(item: Item) { Object.assign(this, item); }
you can do use something like this.
const newdata = olddata.map((x) => { return { id: Number(x.id), label: x.label }; });
as the converted column will be mapped to the newdata array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With