如何使用csv的行作为Node.js对象的键?

3lxsmp7m  于 2023-03-05  发布在  Node.js
关注(0)|答案(2)|浏览(154)

我需要在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)
b5buobof

b5buobof1#

所以在你改变了你的问题之后,答案是你在回调函数里面定义cardinality_mapping,把它移到回调函数外面,它应该可以工作。

+ const cardinality_mapping = {}
  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)
  })
x8diyxa7

x8diyxa72#

/* load this from file*/
const csv =
  `participant_membership_id
32533
4986
5494
5650
5666
5673
5674
5680
5907
6064
`
const csv_rows = csv.split('\n')
// remove first entry (row with the column titles)
csv_rows.shift();

const result = {}
for (const row of csv_rows) {
  const fields = row.split(',')
  const participant_membership_id = fields[0]
  result[participant_membership_id] = 0
}

document.write(JSON.stringify(result, null, 4))

相关问题