How to convert an object vector to another object?

4

I wanted to know if there is any simple way to convert a vector of objects A to a vector of objects of type B, which follow the second structure:

Object A

{
    aId: number;
    aNome: string;
    aDesc: string;
}

Object B

{
    bId: number;
    bNome: string;
}

I'm going to get a vector of A and I want to pass a vector of B, is there any simple method to do this?

    
asked by anonymous 01.11.2017 / 18:07

1 answer

3

It's easy, just use map()

var result = arr.map((item) => new ObjetoB(item.aId, item.aNome));

Complete code - I used constructors in classes to make reading easier.

class ObjetoA {
    constructor(public id, public nome, public desc) {}
}

class ObjetoB {
    constructor(public id, public nome) {}
}

var arr = [new ObjetoA(1, 'A', 'AA'), new ObjetoA(2, '2A', '2AA')];

var result = arr.map((item) => new ObjetoB(item.id, item.nome));

console.log(result);
    
01.11.2017 / 18:24