How to export objects to a CSV file using pure JavaScript All In One
如何使用纯 JavaScript 将对象导出到 CSV 文件
CSV
CSV 使用
,
/逗号
分隔
CSV file separator
CSV 文件分隔符
Comma-separated values (CSV)
Comma-separated values, a file format and extension
逗号分隔值、文件格式和扩展名
https://en.wikipedia.org/wiki/Comma-separated_values
https://en.wikipedia.org/wiki/CSV
solution
const obj = {
0: ["1405", "text string 1 #something"],
1: ["1366", "text string 2 #hashtag"],
603: ["92", "text string 603"],
};
const autoDonwload = (obj) => {
let result = `Views, Title`;
for(const key in obj) {
const [num, str] = obj[key];
result += `\n`;
result += `${num}, ${str}`;
}
console.log(`result =\n`, result);
const blob = new Blob([result], { type: "text/csv; charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "export.csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
demos
<iframe allowfullscreen="true" allowtransparency="true" frameborder="no" height="408.23382568359375" loading="lazy" scrolling="no" src="https://codepen.io/xgqfrms/embed/xxmodaB?default-tab=result&theme-id=dark" style="width: 100%" title="Untitled"> See the Pen Untitled by xgqfrms (@xgqfrms) on CodePen. </iframe>https://codepen.io/xgqfrms/pen/xxmodaB?editors=1011
![](/i/l/?n=23&i=blog/740516/202310/740516-20231017144546167-1303533680.png)
![image](https://user-images.githubusercontent.com/7291672/275735806-77054f7e-edd6-4865-9bd2-226752d0d5fa.png)
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/sEgtw.png