I am using this package xlsx
Wanted to export nested array of object export in excel sheet example added below, please help!
let data = [
{
"product": "Test Product",
"id": 1,
"childProduct": [
{ name: "Child Product 1", "id": 11 },
{ name: "Child Product 2", "id": 12 }
]
},
{
"product": "Test Product",
"id": 1,
"childProduct": [
{ "name": "Child Product 1", "id": 13 },
{ "name": "Child Product 2", "id": 14 }
]
}
]
I have tried this solutions, but it isn't work it always replace last data.
let wb = xlsx.utils.book_new();
data.map((item: any) => {
xlsx.utils.json_to_sheet(item.childProduct);
})
Single sheet should be like this:
I am not sure if there is a more elegant way to do this with built-in xlsx library methods, but you can transform data to get desired output.
Array you pass into json_to_sheet function has to be structured like this:
[
{ "name": "Child Product 1", "id": 11 },
{ "name": "Child Product 2", "id": 12 },
{ "name": "--", "id": "--" },
{ "name": "name", "id": "id" },
{ "name": "Child Product 1", "id": 13 },
{ "name": "Child Product 2", "id": 14 }
]
Transform data into new array for export:
const exportData = data.map((item, i) => {
if (data.length !== i+1) {
item.childProduct.push({"id": "--", "name": "--"});
item.childProduct.push({"id": "id", "name": "name"});
}
return item.childProduct;
}).flat();
Export data using library:
xlsx.utils.json_to_sheet(exportData);
let dummyArray =[]
data.map((dat)=>{
dat.childProduct.forEach((x)=>{
dummyArray.push(x)
})
});
xlsx.utils.json_to_sheet(dummyArray)
This is for simple format.