我需要在Node.js中创建一个Map,将一系列ID从csv匹配到一个数字。
csv文件如下所示:
participant_membership_id
32533
4986
5494
5650
5666
5673
5674
5680
5907
6064
...
我需要这样的Map:
{
32533: 0
4986: 0
5494: 0
...
}
默认值为0。
我到了我有一个Map作为输出的部分:
fs.createReadStream("./data/participant__memberships_ids_mysql.csv")
.pipe(csv())
.on("data", (data) => {
csv_ids.push(data)
})
.on("end",()=>{
const cardinality_mapping = {}
for (const row of csv_ids) {
const keys = Object.values(row)
cardinality_mapping[keys[0]] = 0
}
console.log(cardinality_mapping)
})
我得到了想要的结果:
'33597': 0,
'33598': 0,
'33599': 0,
'33600': 0,
'33601': 0,
'33602': 0,
'33603': 0,
'33604': 0,
'33605': 0,
'33606': 0,
'33607': 0,
'33608': 0,
'33609': 0,
'33610': 0,
'33611': 0,
'33612': 0,
'33613': 0,
'33614': 0,
'33615': 0,
问题是,当我想在代码的后面访问这个对象时,例如使用
console.log(cardinality_mapping)
它告诉我对象不存在。我做错了什么?
附加我的整个代码:
const { DateTime } = require("luxon")
const _ = require("lodash")
const { db } = require("./firebase")
const fs = require("fs")
const csv = require("csv-parser")
const csv_ids = []
let cardinality_mapping = {}
//const csv_rows = csv_ids.split('\n')
//console.log(csv_rows)
fs.createReadStream("./data/participant__memberships_ids_mysql.csv")
.pipe(csv())
.on("data", (data) => {
csv_ids.push(data)
})
.on("end",()=>{
const cardinality_mapping = {}
for (const row of csv_ids) {
const keys = Object.values(row)
cardinality_mapping[keys[0]] = 0
}
console.log(cardinality_mapping)
})
console.log(cardinality_mapping)
2条答案
按热度按时间b5buobof1#
所以在你改变了你的问题之后,答案是你在回调函数里面定义
cardinality_mapping
,把它移到回调函数外面,它应该可以工作。x8diyxa72#