当将csv读入javascript字典时,如何连接其他重复键的值?我已经看到了如何使用bash,c#和perl进行此操作的答案,但我无法找到Javascript的答案。这就是我所拥有的:
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
subjects[data[i].Id] = data[i].VALUE;
}
console.log(subjects);
});
这显然是在现有密钥上写的。相反,我希望密钥是值的数组。 csv基本上看起来像:
Id, VALUE
id1, subject1
id2, subject1
id1, subject3
我想输出为:
{"id1": ["subject1", "subject3"], "id2": ["subject1"]...}
答案 0 :(得分:2)
只检查输出是否已有密钥,如果是,则将新值添加到数组中。否则你创建一个数组。
d3.csv("test.csv", function(data) {
var subjects = {};
for (var i = 0; i < data.length; i++)
{
// Check if key already exists
if(subjects.hasOwnProperty(data[i].Id)){
// push data to array
subjects[data[i].Id].push(data[i].VALUE);
}else{
// create new key and array
subjects[data[i].Id] = [data[i].VALUE];
}
}
console.log(subjects);
});
答案 1 :(得分:1)
您可以将其转换为数组,然后将内容推送到该数组中 var subject = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
//first time we see this id, turn it into an array
if(typeof subjects[data[i].Id] != "object"){
subjects[data[i].Id] = [];
}
//push content to the array
subjects[data[i].Id].push(data[i].VALUE);
}
console.log(subjects);
});
答案 2 :(得分:0)
在for
循环中尝试此操作:
typeof subjects[data[i].Id] == 'undefined' && (subjects[data[i].Id] = []);
subjects[data[i].Id].push(data[i].VALUE);
答案 3 :(得分:0)
如果您使用reduce
:
var out = data.reduce((p, c) => {
const id = c.Id;
p[id] = p[id] || [];
p[id].push(c.VALUE);
return p;
}, {});
RESULT
{
"id1": [
"subject1",
"subject3"
],
"id2": [
"subject1"
]
}