在JavaScript中,将文本文件读入对象数组通常涉及以下几个步骤:
FileReader
API读取文件内容。以下是一个将CSV文件读入对象数组的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Read CSV to Object Array</title>
</head>
<body>
<input type="file" id="fileInput" accept=".csv" />
<script>
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const text = e.target.result;
const data = csvToObjectArray(text);
console.log(data);
};
reader.readAsText(file);
});
function csvToObjectArray(csvText) {
const lines = csvText.split('\n');
const headers = lines[0].split(',');
const result = [];
for (let i = 1; i < lines.length; i++) {
const obj = {};
const currentline = lines[i].split(',');
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
return result;
}
</script>
</body>
</html>
change
事件。FileReader
读取文件内容。csvToObjectArray
函数,将CSV文本转换为对象数组。FileReader
中指定编码格式:FileReader
中指定编码格式:通过以上方法,可以有效地将文本文件读入对象数组,并处理常见的解析问题。
领取专属 10元无门槛券
手把手带您无忧上云