如何将.csv文件转换为字典的javascript数组?每个字典的键是.csv文件中的列标题,项是值

ufj5ltwl  于 2022-12-06  发布在  Java
关注(0)|答案(1)|浏览(146)

例如,如果我有一个.csv文件,其中列标题在文件的第一行中提到,它们的后续值在后面的行中指定,

index,id,description,component,service
0,5,lorem ipsum,7326985,Field Service
gg58donl

gg58donl1#

第一步是分离数据和列标题。我将假设csv在程序中存储为一个字符串数组,每个字符串代表一行,即

const csv = [
  "index,id,description,component,service",
  "0,5,lorem ipsum,7326985,Field Service"
]

如果您的CSV还没有以这种方式表示,您可以使用fs模块来实现:

const fs = require('fs');

fs.readFile('./data.csv', (err, data) => {
  if (err) {
    throw new Error(err);
  }

  const csv = String(data) // convert the buffer to a string
    .split('\n') // Split the string into an array where each item contains one line
    .filter(Boolean); // Remove any empty lines

  // Do the rest of the operations on the CSV data here
});

在这种情况下,我们可以使用spread运算符轻松地将它们拆分,然后在逗号上拆分每个字符串:

const [ headers, ...data ] = csv.map(row => row.split(','));

现在我们的对象看起来像这样:

// headers
[ 'index', 'id', 'description', 'component', 'service' ]

// data
[ 
  [ '0', '5', 'lorem ipsum', '7326985', 'Field Service' ]
]

现在我们可以继续将数据数组中的每个数组Map到一个对象,使用每个值的索引将其Map到CSV中的特定标题。

data.map(row => {
  const rowObject = {};
  row.forEach((value, index) => {
    rowObject[headers[index]] = value;
  });
  return rowObject
});

当然,我们必须将这个Map的数据对象返回到某个地方,或者将它赋给一个新的变量,因为Array.map()函数不会更新原始数组,而是创建一个新数组。将所有这些放在一个代码片段中,看起来如下:

const csv = [
  "index,id,description,component,service",
  "0,5,lorem ipsum,7326985,Field Service"
];

function csvToJSON(csv) {
  const [headers, ...data] = csv.map(row => row.split(','));
  return data.map(row => {
    const rowObject = {};
    row.forEach((value, index) => {
      rowObject[headers[index]] = value;
    });
    return rowObject
  });
}

console.log(csvToJSON(csv));

相关问题