How to convert an object vector to another object?

Asked

Viewed 660 times

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 receive a vector of A and I want to pass a vector of B, is there some simple method of doing this?

  • Why so much negative?

  • I ask myself the same question... I need to improve the description of something? .___.

1 answer

3


It’s easy, just use one map()

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

Full Code - I used constructors in the classes for easy reading.

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);
  • But I always have to solve this in the constructor? There is no automatic way to associate it, right?

  • 1

    Not automatic. It has how to do with serialization, but it is much more common that be more problem than solution.

  • My question was whether this was the simplest way... It seems so, I’ll take it as an answer.

  • 1

    @Felipeavelar What you can understand from your question is that you want to take an array and transform all its items to another array. She doesn’t specifically talk about copying.

  • It’s not a copy I want, that’s exactly what you did, I just wanted to see if there was a simpler way, but from what I researched and from your answer, it really seems to be the simplest way. (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.