diff --git a/packages/csv-parse/lib/index.js b/packages/csv-parse/lib/index.js index 4aefe2a26..ab5538d62 100644 --- a/packages/csv-parse/lib/index.js +++ b/packages/csv-parse/lib/index.js @@ -101,13 +101,11 @@ const parse = function () { const parser = new Parser(options); if (callback) { const records = - options === undefined || options.objname === undefined - ? [] - : Object.create(null); + parser.options.objname === undefined ? [] : Object.create(null); parser.on("readable", function () { let record; while ((record = this.read()) !== null) { - if (options === undefined || options.objname === undefined) { + if (parser.options.objname === undefined) { records.push(record); } else { Object.assign(records, { diff --git a/packages/csv-parse/lib/sync.js b/packages/csv-parse/lib/sync.js index d0298920f..030642544 100644 --- a/packages/csv-parse/lib/sync.js +++ b/packages/csv-parse/lib/sync.js @@ -5,8 +5,9 @@ const parse = function (data, opts = {}) { if (typeof data === "string") { data = Buffer.from(data); } - const records = opts && opts.objname ? Object.create(null) : []; const parser = transform(opts); + const records = + parser.options.objname === undefined ? [] : Object.create(null); const push = (record) => { if (parser.options.objname === undefined) records.push(record); else { diff --git a/packages/csv-parse/test/option.objname.js b/packages/csv-parse/test/option.objname.js index 5329dbdda..261873a3c 100644 --- a/packages/csv-parse/test/option.objname.js +++ b/packages/csv-parse/test/option.objname.js @@ -1,5 +1,7 @@ import "should"; +import assert from "node:assert/strict"; import { parse } from "../lib/index.js"; +import { parse as parseSync } from "../lib/sync.js"; describe("Option `objname`", function () { describe("validation", function () { @@ -11,4 +13,30 @@ describe("Option `objname`", function () { ); }); }); + + describe("normalized result mode", function () { + it("returns a dictionary with the first column as key", function () { + const records = parseSync("alice,A\nbob,B", { objname: 0 }); + assert.deepEqual( + records, + Object.assign(Object.create(null), { + alice: ["alice", "A"], + bob: ["bob", "B"], + }), + ); + }); + + for (const objname of [null, false]) { + it(`returns complete array records with objname ${objname}`, function (next) { + parse("alice,A,extra\nbob,B,extra", { objname }, (err, records) => { + if (err) return next(err); + assert.deepEqual(records, [ + ["alice", "A", "extra"], + ["bob", "B", "extra"], + ]); + next(); + }); + }); + } + }); });