49

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?

3 Answers 3

61

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)


Edit

This can be shorter with Object.assign:

constructor(item: Item) {
    Object.assign(this, item);
}
Sign up to request clarification or add additional context in comments.

Comments

16

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.

2 Comments

How is { id: Number(...), label: ... } related to the required ViewItem class from the question? The two existing answers from 2016 and 2017 also use Array.map but actually answer the question because they actually return ViewItem instances.
@MartijnPieters - maybe different POV, I liked this answer, I interpreted newdata being the array of ViewItem. maybe the answer could have used SO's exact parameters naming.
3

An alternate method is to use Object.keys,

class Item {
    name: string;
    desc: string;
    meta: string
}

class ViewItem {
    name: string;
    desc: string;
    hidden: boolean;

    // additional properties
    additionalProp: boolean;

    constructor(item: Item) {
        Object.keys(item).forEach((prop) => { this[prop] = item[prop]; });

        // additional properties specific to this class
        this.additionalProp = false;
    }
}

Usage:

let arr1: Item[] = [
    {
        name: "John Doe",
        desc: "blah",
        meta: "blah blah"
    }
];
let arr2: ViewItem[] = arr1.map(item => new ViewItem(item));

Playground link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.