简体   繁体   English

如何用JS中的对象元素填充CSV文件

[英]How to fill CSV file with object elements in JS

I've got an object and I'd like to put the elements of this object into a CSV file, however when I'm trying to get the key of the object it gives back a type error: Uncaught TypeError: Cannot convert undefined or null to object.我有一个对象,我想将此对象的元素放入 CSV 文件中,但是当我尝试获取对象的键时,它返回一个类型错误:未捕获的类型错误:无法转换未定义或空对象。

When I console log the object it actually shows all the elements but for some reason I can't get the key and values back.当我控制台记录对象时,它实际上显示了所有元素,但由于某种原因,我无法取回键和值。

This is how I console logged the object: console.log(JSON.stringify(records));这是我控制台记录对象的方式: console.log(JSON.stringify(records));

And here is what I get back: {"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}这是我得到的回复: {"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}

Here is the full js function:这是完整的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;

Here is how I parse the object to js from thymeleaf:以下是我从 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>

In your case, you're expecting records to be an array, but it's an object (perhaps one value in the array).在您的情况下,您希望记录是一个数组,但它是一个对象(可能是数组中的一个值)。 Additionally, fields such as coInvestistigators are an array, not string, which is a separate case you'll need to handle.此外,诸如coInvestistigators类的字段是一个数组,而不是字符串,这是您需要处理的单独情况。

You're accessing records[0] , which means you're trying to access { 0: <some_value> } in your JSON object.您正在访问records[0] ,这意味着您正在尝试访问 JSON 对象中的{ 0: <some_value> } In your case, records isn't an array and it doesn't contain the key 0 so records[0] is undefined .在您的情况下, records不是数组并且它不包含键0因此records[0]undefined

Object.keys takes in a Javascript object and returns all the keys in an array. Object.keys接受一个 Javascript 对象并返回数组中的所有键。

This means that Object.keys(records[0]) would cause an error since the value of records[0] is undefined.这意味着Object.keys(records[0])将导致错误,因为records[0]值未定义。

Object.keys(records) would return ["id", "title", "status", ...] Object.keys(records)将返回["id", "title", "status", ...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM