我正在将不同的指标 CSV 文件加载到 JavaScript 中,例如:
CSV for population:
id,year,value
AF,1800,3280000
AF,1820,3280000
AF,1870,4207000
AG,1800,37000
AG,1851,37000
AG,1861,37000
对于每个指标文件,我需要:
- 填补每个实体缺失的年份 (id)
- 找出每个实体的时间跨度
- 找出每个实体的最小值和最大值
- 找到指标的时间跨度
- 找到指标的最小值和最大值
执行这些操作的廉价方法是什么?或者,是否有一个很好的 JavaScript 库来执行这些常见的数据操作并将数据有效地存储在各种对象表示中?
我希望上述文件的最终表示类似于:
data = {
population : {
entities :
AF : {
data : {
1800 : 3280000,
1801 : 3280000,
},
entity_meta : {
start : 1800,
end :
min :
max :
},
[...]
indicator_meta : {
start : 1700,
end :
min :
max :
}
[...]
谢谢!
最佳答案
让我们假设您在二维数组中有 CSV 数据:
var data = [[AF,1800,3280000],
[AF,1820,3280000],
[AF,1870,4207000],
[AG,1800,37000],
[AG,1851,37000],
[AG,1861,37000]]
对于这个例子,我将使用 jQuerys 实用函数,因为它会使工作变得容易得多,而且没有任何实际开销。
// we will loop thru all the rows
// if the id does not belong to the entities then we will add the property.
// if the property does exist then we update the values
var entities = {}
$.each(data, function (i, n) {
// set property
if (!entities[n[0]]) {
entities[n[0]] = {
data : {
n[1]: n[2]
},
entity_meta: {
start: n[1],
end: n[1]
min: n[1]
max: n[1]
}
}
// update property
} else {
// add new data property
entities[n[0]]['data'][n[1]] = n[2];
// if the property should change then update it
if ( entities[n[0]]['entity_meta']['min'] > n[1] ) {
entities[n[0]]['entity_meta']['min'] = n[1];
}
}
});
这显然不是所有代码,但它应该清楚地解释应该采用的方法。
也不是说您预期的最终对象结构非常过于复杂您应该在适当的地方真正使用数组,尤其是对于实体
和数据
。
关于javascript - JavaScript 中 CSV 数据的数据操作(填充、最小、最大)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7051468/