从CSV动态创建对象 [英] Create object on the fly from CSV
问题描述
我要做的是动态创建一个具有动态属性的对象文字。
What I'm trying to do is create a object literal on the fly with dynamic properties.
我有一个包含内容(CSV格式)的数组文件。
I have an array containing the content (CSV format) of a file.
每个元素都是一行(内容用 / \r?\ n /
拆分)。
Each element is one line (the content was split with /\r?\n/
).
该数组的第一个元素(第一行)包含我想要的对象文字参数,用逗号分隔。
The first element (first line) of that array contains the parameters I want to have for my object literal, separated by commas.
所有其他元素都是第一行中设置的参数值(仍然是CSV格式)。
All the other elements are values (still CSV format) of the parameters set in the first line.
我目前的代码如下:
function jsonDataArray(array) {
var jsonResult = [],
parameters = [],
values;
for(var i=0; i < array.length; i++) {
if(i === 0) {
var parameters = array[i].split(',');
var objJSON = {};
for(var k=0; k < parameters.length; k++) {
objJSON.eval(parameters[k]);
}
continue;
}
values = array[i].split(',')
for(var j=0; j < objJSON.length; j++) {
objJSON[j] = values;
}
jsonResult.push(objJSON);
}
return jsonResult;
}
现在,当我在节点中启动此代码时, objJSON.eval(parameters [k])
line似乎是问题所在,但我无法解决问题。
Now when I launch this code in node, the objJSON.eval(parameters[k])
line seems to be the one where the problem is, but I wasn't able to solve the problem.
所以基本上我的问题如下:
So basically my questions are the following :
-
我应该如何继续将第一行的参数设置为JSON对象的参数+填充其他行的值?
How should I proceed to have the parameters from the first line set as parameters of a JSON object + fill the values of the other lines in ?
使用以下方法解析新行是否安全: / \ r?\ n /
?
Is it safe to parse new lines with this : /\r?\n/
?
提前感谢您的帮助!
编辑:我错误地使用术语JSON来表示对象文字,所以我更正了问题。我没有修改函数,所以我没有错误地在代码中添加错误。
EDIT : I mistakenly used the term JSON to mean object literal so I corrected the question. I didn't modify the function though so that I don't add errors in the code by mistake.
推荐答案
它看起来我想要一个对象数组,每个对象都有第一行的键(标题)。
It looks to me you want an array of objects, each object having keys from the first row (headers).
以下代码假设您已经通过<$将csv打破到每一行c $ c> \ r?\ n
The following code assumes you already broke the csv into each line via \r?\n
(function() {
var csv = [];
csv.push('name,age,gender');
csv.push('jake,13,m');
csv.push('sarah,15,f');
csv.push('john,18,m');
csv.push('nick,13,m');
console.log(csv);
function jsonDataArray(array) {
var headers = array[0].split(',');
var jsonData = [];
for ( var i = 1, length = array.length; i < length; i++ )
{
var row = array[i].split(',');
var data = {};
for ( var x = 0; x < row.length; x++ )
{
data[headers[x]] = row[x];
}
jsonData.push(data);
}
return jsonData;
}
console.log(jsonDataArray(csv));
})();
http://jsbin.com/igiwor/2/edit
这将产生如下内容:
[{ name="jake", age="13", gender="m"},
{ name="sarah", age="15", gender="f"},
{ name="john", age="18", gender="m"},
{ name="nick" age="13", gender="m"}]
这篇关于从CSV动态创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!