我正在从 bigquery 获取数据,我需要将其作为整数存储在 MongoDB 中,以便我可以在 Mongo 中对该数据执行操作。尽管bigquery中列的数据类型是Integer,但它的nodejs api在其Javascript对象中返回字符串。例如。我得到的结果类似于 [{row1:'3',row2:'4',row3:'5'},{row1:'13',row2:'14',row3:'15' }...]
typeof
给出对象每个元素的字符串。我可以运行一个循环并将每个元素转换为整数,但这在数据集上不可扩展。另外,我不希望所有字符串都转换为整数,只希望将那些在 bigquery 中作为整数存储的字符串转换为整数。我在nodejs中使用gcloud模块来获取数据。
最佳答案
假设您知道类型属性在响应中的位置,类似这样的事情就可以了。
var response = [{type: 'Integer', value: '13'} /* other objects.. */];
var mappedResponse = response.map(function(item) {
// Put your logic here
// This implementation just bails
if (item.type != 'Integer') return item;
// This just converts the value to an integer, but beware
// it returns NaN if the value isn't actually a number
item.value = parseInt(item.value);
// you MUST return the item after modifying it.
return item;
});
这仍然会循环遍历每个项目,但如果它不是我们正在寻找的内容,则会立即退出。还可以组合多个 map 和过滤器来概括这一点。
解决这个问题的唯一方法是首先应用过滤器,但这基本上实现了与我们初始类型检查相同的效果
var mappedResponse = response
// Now we only deal with integers in the map function
.filter(x => x.type == 'Integer)
.map(function(item) {
// This just converts the value to an integer, but beware
// it returns NaN if the value isn't actually a number
item.value = parseInt(item.value);
// you MUST return the item after modifying it.
return item;
});
关于javascript - 如何从 bigquery nodejs api 获取整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35426831/