gpt4 book ai didi

javascript - 从 csv 创建具有正确格式的对象

转载 作者:行者123 更新时间:2023-12-03 06:45:30 24 4
gpt4 key购买 nike

我有一个 csv 文件:

name,number,level
Mike,b1,0
Tom,b2,0
.....

我想构建类似的东西:

    matrix: { 

{ name: 'Mike', number: 'b1', level: 0 },
{ name: 'Tom', number: 'b2', level: 0 },
....
}

我希望能够提取属性,例如matrix.name

我的问题是我想稍后使用 ejs 文件按名称进行搜索。

最佳答案

我假设您已经加载了 CSV 数据。如果没有,you can refer to this question关于如何将该数据加载到您的应用程序中。

从这里开始,我假设您的数据存储在名为 csv 的变量中。您需要做的是首先处理该数据的每一行并用逗号分隔值。之后,就像创建一个新对象(其中每个值)并将该对象添加到数组一样简单。

var csv = 'name,number,level\n' +
'Mike,b1,0\n' +
'Tom,b2,0';

// Split the data into individual lines by splitting on the line break
var lines = csv.split('\n');

// I'm going to store the column names so I can use them to automatically get each value
// Note that I also removed the columns from the `lines` array so it won't be there when we go through it
var columns = lines.shift();

// Make sure we split on the commas
columns = columns.split(',');

// Create an array for us to store the objects in
var matrix = [];

// Next, we begin processing each line
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];

// Each value is separated by a comma. Split the line on those commas
var values = line.split(',');

// Now we create a new object that we'll store each value in
var obj = {};

// Remember that `columns` array? We're going to use that to generate our keys
for (var j = 0, numOfColumns = columns.length; j < numOfColumns; j++) {
// This is going to be 'name', 'number', and 'level'
var column = columns[j];

// Here is where we extract the matching value
var value = values[j];

// Now we add a new property to that new object using the `column` as the key
// and the `value` as, well, the value
obj[column] = value;
}

// The object has been generated, add it to the array
matrix.push(obj);
}

// Display the complete array
document.querySelector('pre').innerText = JSON.stringify(matrix, null, 2);
<pre></pre>

关于javascript - 从 csv 创建具有正确格式的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com