[英]How to Convert nested JSON into excel in nodejs
I am trying to convert the below JSON into excel, I am using XLSX for it, it is converting my JSON to excel but, the nested array of dailyPointsArray is blank after converting into excel.
试过的代码
const XLSX = require("xlsx");
const workSheet = XLSX.utils.json_to_sheet(attendanceData);
const workBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workBook, workSheet, "attendance");
XLSX.write(workBook, { bookType: "xlsx", type: "buffer" });
XLSX.write(workBook, { bookType: "xlsx", type: "binary" });
XLSX.writeFile(workBook,"newExcel.xlsx");
attendanceData:[
{
workerId: '1230',
workerFullName: 'A',
workerDepartment: 'INFORMATION TECHNOLOGY',
workerDesignation: 'ASSISTANT MANAGER',
Location: 'locationA',
dailyPointsArray: [
{
inTime: '-',
Date: '23/03/2022',
outTime: '-',
Points: null,
createdAs: 'ABSENT'
},
{
inTime: '-',
Date: '24/03/2022',
outTime: '-',
Points: null,
createdAs: 'ABSENT'
}
],
total_duration: 0,
total_shift_points: 0
},
{
workerId: '1128',
workerFullName: 'B',
workerDepartment: 'INFORMATION TECHNOLOGY',
workerDesignation: 'MANAGER',
Location: 'LocationA',
dailyPointsArray: [
{
inTime: '-',
Date: '23/03/2022',
outTime: '-',
Points: null,
createdAs: 'ABSENT'
},
{
inTime: '-',
Date: '24/03/2022',
outTime: '-',
Points: null,
createdAs: 'ABSENT'
}
],
total_duration: 17,
total_shift_points: 2
},
]
尝试展平数组:过滤嵌套数组,按您想要的顺序获取您想要的键
尝试这个:
const filtered = attendanceData.map(obj => {
// get totals to add them later to keep column order (or use `header` param for columns order)
const {
dailyPointsArray,
total_duration,
total_shift_points,
...rest
} = obj;
// flatten..
dailyPointsArray.map(el => {
rest[el['Date']] = el.createdAs;
});
return {...rest,
total_duration,
total_shift_points
};
});
const XLSX = require("xlsx");
const workSheet = XLSX.utils.json_to_sheet(filtered);
const workBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workBook, workSheet, "attendance");
XLSX.write(workBook, { bookType: "xlsx", type: "buffer" });
XLSX.write(workBook, { bookType: "xlsx", type: "binary" });
XLSX.writeFile(workBook,"newExcel.xlsx");
您还可以使用 typeof 运算符
const mappedArr = attendanceData.map(item => {
if (item.dailyPointsArray == null) {
item.dailyPointsArray = "";
} else if (typeof item.dailyPointsArray == "object") {
item.dailyPointsArray = JSON.stringify(item.dailyPointsArray);
}
return {
...item,
item.dailyPointsArray
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.