javascript - 如何在 JS 中用对象元素填充 CSV 文件
问题描述
我有一个对象,我想将此对象的元素放入 CSV 文件中,但是当我尝试获取对象的键时,它会返回类型错误:Uncaught TypeError: Cannot convert undefined or null 反对。
当我控制台记录对象时,它实际上显示了所有元素,但由于某种原因,我无法取回键和值。
这就是我控制台记录对象的方式:console.log(JSON.stringify(records));
这是我回来的:{"id":"5e7b389911c2125dfaf2b5f2","title":"Example Application Number 1","status":"Ready For Submission","principalInvestigator":"Mr. Harry Styles","coInvestigators":["Niall Horan, Liam Payne, Zayn Malik, Louis Tomilson"],"partners":null,"funder":"Innovate UK","researchGroup":"AHIVES","scheme":"GCRF","requestedAmount":null,"estimatedAmount":1234,"submissionDate":"2020-03-23T00:00:00.000+01:00","startDate":"2020-03-29T00:00:00.000+01:00","estimatedDuration":null,"endDate":null,"facility":null,"comments":null,"dateCreated":"2020-03-25T11:55:21.902+01:00","lastUpdated":"2020-03-25T11:55:21.902+01:00","dateDeleted":null}
这是完整的js函数:
window.downloadCsv = function(records) {
console.log(JSON.stringify(records));
// Use first element to choose the keys and the order
let keys = Object.keys(records[0]);
// Build header
let result = keys.join("\t") + "\n";
// Add the rows
records.forEach(function(obj){
result += keys.map(k => obj[k]).join("\t") + "\n";
});
return result;
这是我将对象从 thymeleaf 解析为 js 的方法:
<button title="Downloads the data from the query into a CSV"
class="inline-flex items-center bg-red-600 text-white font-bold px-4 py-1
rounded shadow hover:bg-red-500"
type="submit"
th:onclick="downloadCsv(/*[[${record}]]*/)">
<span>Download</span>
<svg class="fill-current w-4 h-4 ml-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z" /></svg>
</button>
解决方案
在您的情况下,您期望记录是一个数组,但它是一个对象(可能是数组中的一个值)。此外,诸如字段之类的字段coInvestistigators
是数组,而不是字符串,这是您需要处理的单独情况。
您正在访问records[0]
,这意味着您正在尝试访问{ 0: <some_value> }
JSON 对象。在你的情况下,records
is 不是一个数组,它不包含密钥0
所以records[0]
is undefined
。
Object.keys
接受一个 Javascript 对象并返回一个数组中的所有键。
这意味着这Object.keys(records[0])
将导致错误,因为 的值records[0]
未定义。
Object.keys(records)
会回来["id", "title", "status", ...]
推荐阅读
- git - Git 正在检测我根本没有接触过的文件中的更改?
- ios - 我应该使用依赖注入而不是类函数吗?
- android - Android 中定时作业执行的当前最佳实践
- mysql - 如何为给定的列和几行插入随机整数
- kubernetes - 在 IBM-Cloud 的 K8saaS 中使用预安装的 fluentd 安装?
- scala - 在 http4s 中发送 JSON 响应的正确方法是什么?
- python - Python 的 json.load 奇怪的行为
- java - -XX:+StressLCM, -XX:+StressGCM JVM 选项
- c# - 如何生成静态文件的 URL(就像 ASP.NET Core UrlHelper 为操作方法所做的那样)?
- laravel - 使用 vuejs 和 laravel 上传文件