如何将csv文件中的数据导入到JavaScript字典中?

时间:2019-01-23 18:11:45

标签: javascript html csv dictionary

我正在尝试使用具有四列的csv文件在javascript中创建字典。我希望键是A列中的内容,而值是包含B:D列内容的列表。

例如,csv文件如下所示:      A B C D “ face.jpg”“老”“女”“快乐” “ face2.jpg”“老”“男”“快乐”

我希望字典看起来像这样:

faceDict = {face.jpg:[“ Old”,“ Female”,“ Happy],face2.jpg:[” Old“,” Male“,” Happy]}

有没有办法在javascript中做到这一点?非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我使它可以在Windows上的Chrome中运行(有一些不必要的步骤。)

csv具有以下内容:

 "1" "b" "c" "d"
 "2" "f" "g" "h"

使用文本编辑器打开文件,然后将内容粘贴到脚本中,然后用反引号将字符串引起来:

const csv = `1,b,c,d
2,f,g,h`;

这是完整的脚本:

<html>
<script>

const csv = `1,b,c,d
2,f,g,h`;

// Replaces newline characters with commas
const csvModified = csv.replace(/\n/g, ",");

// Converts the string to an array 
const arr = csvModified.split(",");

//Separates the keys and values into their own arrays (assuming every 4th item is a key) 
let keys = [], vals = [];
for(i = 0; i < arr.length; i++){
  if(i % 4 == 0){ keys.push(arr[i]); }
  else { vals.push(arr[i]); }
}

// Makes a javascript object (i.e. a dictionary) from the two arrays
const dict = {};
for(i = 0; i < keys.length; i++){
  localVals = vals.splice(0,3); // Extracts the first three items as a new array
  dict[keys[i]] = localVals; // Adds a property (named for the key) to the object
}

// Prints the object to the browser console
console.log(dict);

</script>
</html>

对象看起来像:

{
  1: ["b", "c", "d"]
  2: ["f", "g", "h"]
}