As the title says:
I have the following class:
export class Producto{
nombre: string;
cantidad: number;
precio: number;
constructor(){
//...
}
}
and I want to pass an Array of the objects of this same class:
[Producto, Producto, Producto, Producto]
to an Array of Javascript objects:
[
{
nombre:"azucar",
cantidad: 5,
precio: 2.90
},
{
nombre:"pan",
cantidad: 2,
precio: 0.90
},
{},
....
]
Is there any method or function that will help me to do it?
It is enough for me to just convert a single object. Obviously if you can with one then it's a matter of iterating with the others. But better if there is some method for everything...
Help is greatly appreciated...
With the JSON.stringify and JSON.parse methods you should be able to achieve what you want:
First, the array of elements of type "Product" is transformed into a string in JSON format, and then it is converted to an array of elements of type "Object" again.
you can iterate the array of objects in several ways but for your case I usually use forEach
Another possible solution would be using
Object.assign
: