我有一个包含以下数据的 csv
this_year | minus_one_year | minus_two_year | minus_three_year
-------------------------------------------------------------------------
1 | 2 | 2 | 3
-------------------------------------------------------------------------
4 | 5 | 5 | 5
-------------------------------------------------------------------------
2 | 2 | 2 | 2
-------------------------------------------------------------------------
4 | 5 | 4 | 4
-------------------------------------------------------------------------
1 | 2 | 3 | 3
-------------------------------------------------------------------------
我读了这个 csv 文件,现在我需要组织数据。我的最终目标是获得以下输出
{
"nodes": [
{
"name": "1",
"node": "this_year"
},
{
"name": "2",
"node": "this_year"
},
{
"name": "4",
"node": "this_year"
},
{
"name": "2",
"node": "minus_one_year"
},
{
"name": "5",
"node": "minus_one_year"
},
{
"name": "2",
"node": "minus_two_year"
},
{
"name": "3",
"node": "minus_two_year"
},
{
"name": "4",
"node": "minus_two_year"
},
{
"name": "5",
"node": "minus_two_year"
},
{
"name": "2",
"node": "minus_three_year"
},
{
"name": "3",
"node": "minus_three_year"
},
{
"name": "4",
"node": "minus_three_year"
},
{
"name": "5",
"node": "minus_three_year"
}
]
}
因此,对于每一列,我都获得了唯一的值。所以 this_year 有 3 个节点,因为数据包含 3 个唯一值:1、2 和 4。
我正在使用 D3,但目前这仅涉及解析。对于数据的格式化,我认为我走在正确的轨道上,我正在使用 map 。
到目前为止我有这样的东西
let graph = {"nodes" : [], "links" : []};
graph.nodes = output.map(function(d) { return [
{
'name': d.current_month,
'node': d.value
}
]; });
console.log(graph.nodes)
其中输出是 csv 数据。显然这是行不通的,但是所有这些映射和减少等都让我有点困惑。所以根据我拥有的数据,我怎样才能实现 以上输出?
我已经添加了 JSFiddle展示我到目前为止所做的事情。
非常感谢
更新
d3.csv('churn_status.csv')
.then(function(data) {
vm.graph.nodes = data.reduce(function(acc, line){
return acc.concat(Object.entries(line).map(function(column){
return {name: column[0], node: column[1]}
}))}, []);
vm.graph.nodes = vm.graph.nodes.sort(function(a,b) { return a.name > b.name ? -1 : 1});
})
.catch(function(error){
// handle error
});
最佳答案
这是一种方法,您必须使用 Object.entries()
将行分成键/值,然后将新对象推送到节点。
注意Object.entries({a:100})
返回一个数组["a", 100]
let graph = {"nodes" : [], "links" : []};
output.forEach(function(line) {
Object.entries(line).forEach(function(column){
graph.nodes.push({
'name': column[0],
'node': column[1]
})
})
})
console.log(graph.nodes)
编辑:您还可以使用以类似方式工作的reduce函数
output.reduce(function(acc, line){
return acc.concat(Object.entries(line).map(function(column){
return {name: column[0], node: column[1]}
}))}, [])
关于javascript - 将 CSV 数据映射到新结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54153548/