我正在加载一个大型CSV文件以在javascript中使用-从中创建SVG元素。
变量中有一个称为代码的属性。在CSV中,有一列称为SPECIES。 “代码”和“特殊”包含相同的字母代码。
我希望能够将CSV中的数据与var树进行比较,如果对于CSV中的特定记录,“ SPECIES”字段与变量中的“ code”值相同,我想从变量返回“ common”值。
CSV文件具有150,000条记录,这就是为什么我不想向其添加具有通用名称的另一列的原因。
这是变量的一部分(共有54个对象):
var trees = [
{ code: 'ACPL',
common: 'Norway Maple',
genus: 'Acer',
species: 'platanoides',
family: 'Sapindaceae',
color: '#00567e'
},
{ code: 'ACRU',
common: 'Red Maple',
genus: 'Acer',
species: 'rubrum',
family: 'Sapindaceae',
color: '#0084ff'
},
{ code: 'ACSA1',
common: 'Silver Maple',
genus: 'Acer',
species: 'saccharinum',
family: 'Sapindaceae',
color: '#c3c3c3'
}
];
这是data.csv的一部分(此处总共150,000条记录):
DIAMETER,SPECIES,longitude,latitude
15,ACPL,-73.935944,40.668076
22,ACPL,-73.934644,40.667189
28,ACSA1,-73.941676,40.667593
27,ACPL,-73.935095,40.666322
9,ACRU,-73.941297,40.667574
27,ACPL,-73.935149,40.666324
19,ACRU,-73.933664,40.666244
这是我尝试过的方法,无法正常工作:
var treeCode = trees.forEach(function(each) { return each.code; }); // returns the value of "code" for each object in the trees variable
var treeCommon = trees.forEach(function(each) { return each.common; }); // returns the value of "color" for each object in the trees variable
var tip = d3.tip() // d3.tip is a tooltip library for D3.js
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d){if (d.SPECIES == treeCode){ // the data from the csv was loaded in earlier, and d.SPECIES returns the "SPECIES" field
return treeCommon}
})
任何关于需要做什么的想法将不胜感激!让我知道是否可以澄清任何事情。
完整的代码在这里:https://github.com/jhubley/street-trees/blob/master/index.html
您可以在该代码中看到有一个用十六进制颜色显示的很长的if / else语句。那是我想在哪里使用这种方法的另一个例子。
感谢您的光临!
最佳答案
在http://underscorejs.org/处有一些很好的下划线文档。 D3是一个相当健壮的库,因此我敢肯定,其中一些功能也已经内置在D3中。
为了明确起见,您想遍历CSV中的记录并从tree对象中提取相应的数据。以下是我如何使用下划线进行此操作:
// Information about each tree type
var treeInfo = [
{
code: 'ACPL',
common: 'Norway Maple',
genus: 'Acer',
species: 'platanoides',
family: 'Sapindaceae',
color: '#00567e'
},
...
];
// imported from CSV
var treeList = [
{
DIAMETER: 15,
SPECIES: "ACPL",
longitude: -73.935944,
latitude: 40.668076
}
...
]
// loop through the imported list of trees
_.each(treeList, function(){
// _.each() makes `this`` refer to the object in the list as it loops through
// find the info for this tree species
var info = _.findWhere(treeData, {"code": this.SPECIES});
// insert the keys and values from the info object into the original object from the treeList
_.extend(this, info);
})
//now treeList contains all the corresponding info (by species) from treeInfo for each tree
关于javascript - 合并共享公共(public)键或值的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28120453/