I have the following product object in typescript:
Product:
{
productId: 1,
productName: "ABC",
orders: [{
orderId: 1,
orderDate: "2020-01-01",
amount: 100
},
{
orderId: 2,
orderDate: "2020-01-01",
amount: 200
}],
priceHistory: [{
date: "2020-01-1",
price: 15
},
{
date: "2020-02-1",
price: 16
}],
purchaseHistory: [{
purchaseDate: "2019-01-01",
purchaseAmt: 10,
qty: 20
},
{
purchaseDate: "2019-02-01",
purchaseAmt: 10,
qty: 2
}],
parts: [{
partId: 1,
partName: "Part 1",
priceHistory: [,,,,],
orders: [,,,],
purchaseHistory: [,,,,]
},
{
partId: 2,
partName: "Part 2",
priceHistory: [,,,,],
orders: [,,,],
purchaseHistory: [,,,,]
}]
}
I need to pass the product object to an API without priceHistory and purchaseHistory (from product and parts).
{
productId: 1,
productName: "ABC",
orders: [{
orderId: 1,
orderDate: "2020-01-01",
amount: 100
},
{
orderId: 2,
orderDate: "2020-01-01",
amount: 200
}],
priceHistory: [],
purchaseHistory: [],
parts: [{
partId: 1,
partName: "Part 1",
priceHistory: [],
orders: [,,,],
purchaseHistory: []
},
{
partId: 2,
partName: "Part 2",
priceHistory: [],
orders: [,,,],
purchaseHistory: []
}]
}
How can I achieve this without impacting the original product object? I tried:
let newProduct = originalProduct;
newProduct.priceHistory = [];
newProduct.purchaseHistory = []
newProduct.parts.forEach((part) => {
part.priceHistory = [];
part.purchaseHistory = [];
});
However, it updates the original product object too. I believe we can do this using a spread (...
) operator but I am not sure how can I copy all the properties