我正在学习JS,而且我遇到了问题。
我有一个示例数据集:miserables.js,它采用以下格式:
var miserables = {
nodes:[
{nodeName:"Myriel", group:1},
{nodeName:"Napoleon", group:1},
.....
{nodeName:"Mme. Hucheloup", group:8}
],
links:[
{source:1, target:0, value:1},
{source:2, target:0, value:8},
.....
{source:76, target:58, value:1}
]
};
我正在阅读它,只是用这个
<script type="text/javascript" src="./miserables.js"></script>
它完美无缺。
当我想直接从两个csv文件中读取该信息时,问题出现了:
links1.csv
source target weight
Myriel Napoleon 3
Napoleon Mme. Hucheloup 2
Napoleon Myriel 23
Mme. Hucheloup Myriel 4
... ... ...
nodes2.csv
node group description
Myriel A family A
Napoleon C family B
Mme. Hucheloup C family C
... ... ...
我使用的脚本如下所示,我可以使其工作:
<script>
$(document).ready(function () {
var links = [], nodes = [], links_backup = [];
d3.csv('./links1.csv',function(links_csv) {
return {
source:links_csv.source,
target:links_csv.target,
strength:links_csv.strength,
year:links_csv.year,
type:links_csv.type,
}
},function(csv_data) {
$.each(csv_data,function (idx,row) {
links.push(row)
links_backup.push(row)
})
});
d3.csv('./nodes2.csv',function (nodes_csv) {
var row = {
node:nodes_csv.node,
group:nodes_csv.group,
description_n4:nodes_csv.description_n4,
}
if (nodes_csv.hasOwnProperty('weight')) {
row.weight = nodes_csv.weight
}
return row
},function (data) {
var node_groups = {}
$.each(data,function (idx,row) {
nodes.push(row)
if (!node_groups.hasOwnProperty(row.group)) {
node_groups[row.group] = {
fill: getRandomColor()
}
}
})
})