将json格式转换为csv nodejs

pdsfdshx  于 2023-06-22  发布在  Node.js
关注(0)|答案(2)|浏览(102)

对不起,也许这是重复的,但我找不到解决方案。请帮助:

const data = [
  {
    "Month": "V",
    "6/2022": "2",
    "7/2022": "4",
  },
  {
    "Month": "L",
    "6/2022": "6",
    "7/2022": "8",
  },
];

我需要像csv

Month;V;L
6/2022;2;6
7/2022;4;8

这是我尝试过的,但没有帮助。

"// Extracting headers
const headers = Object.keys(data[0]);

// Extracting data rows
const rows = data.map(item => Object.values(item));

// Writing to CSV file
const csvContent = [headers, ...rows].map(row => row.join(';')).join('\n');
"

谢谢您的帮助。

aor9mmx1

aor9mmx11#

使用Array::reduce()按键收集值并转换为CSV:

const data = [
  {
    "Month": "V",
    "6/2022": "2",
    "7/2022": "4",
  },
  {
    "Month": "L",
    "6/2022": "6",
    "7/2022": "8",
  },
];

const obj = data.reduce((obj, item) => {
    for (const key in item) {
        (obj[key] ??= []).push(item[key]);
    }
    return obj;
}, {});

const csv = Object.entries(obj).map(([key, items]) => key + ';' + items.join(';')).join('\n');

console.log(csv);

和基准:

<script benchmark data-count="1">

    const data = JSON.parse(JSON.stringify(Array.from({ length: 1000000 }).reduce(arr => arr.push(...[
        {
            "Month": "V",
            "6/2022": "2",
            "7/2022": "4",
        },
        {
            "Month": "L",
            "6/2022": "6",
            "7/2022": "8",
        },
    ]) && arr, [])));

    // @benchmark Lin Du's 

    Object.keys(data[0])
        .map(k => [k, ...data.map(v => v[k])].join(';'))
        .join('\n');    

    // @benchmark Alexander's

    const obj = data.reduce((obj, item) => {
        for (const key in item) {
            (obj[key] ??= []).push(item[key]);
        }
        return obj;
    }, {});

    Object.entries(obj).map(([key, items]) => key + ';' + items.join(';')).join('\n');

</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
tcbh2hod

tcbh2hod2#

const data = [
  {
    "Month": "V",
    "6/2022": "2",
    "7/2022": "4",
  },
  {
    "Month": "L",
    "6/2022": "6",
    "7/2022": "8",
  },
];

const csv = Object.keys(data[0])
  .map(k => [k, ...data.map(v => v[k])].join(';'))
  .join('\n');

console.log(csv);

相关问题