Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/csv-parse/lib/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,7 @@ const transform = function (original_options = {}) {
// With columns, records are object
if (columns !== false) {
const obj = {};
const groupedColumns = new Set();
// Transform record array to an object
for (let i = 0, l = record.length; i < l; i++) {
if (columns[i] === undefined || columns[i].disabled) continue;
Expand All @@ -599,10 +600,11 @@ const transform = function (original_options = {}) {
group_columns_by_name === true &&
Object.hasOwn(obj, columns[i].name)
) {
if (Array.isArray(obj[columns[i].name])) {
obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
if (groupedColumns.has(columns[i].name)) {
obj[columns[i].name].push(record[i]);
} else {
obj[columns[i].name] = [obj[columns[i].name], record[i]];
groupedColumns.add(columns[i].name);
}
} else {
Object.defineProperty(obj, columns[i].name, {
Expand Down
29 changes: 29 additions & 0 deletions packages/csv-parse/test/option.group_columns_by_name.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import "should";
import { parse } from "../lib/index.js";
import { parse as parseSync } from "../lib/sync.js";

describe("Option `group_columns_by_name`", function () {
it("require columns to be active", function () {
Expand Down Expand Up @@ -44,4 +45,32 @@ describe("Option `group_columns_by_name`", function () {
},
);
});

it("preserves array-valued casts instead of treating them as groups", function () {
const records = parseSync("1,2,3", {
columns: ["value", "value", "value"],
group_columns_by_name: true,
cast: (value) => [Number(value)],
});
records.should.eql([{ value: [[1], [2], [3]] }]);
});

it("preserves an array-valued cast appended to an existing group", function () {
const records = parseSync("1,2,3", {
columns: ["value", "value", "value"],
group_columns_by_name: true,
cast: (value, context) =>
context.index === 2 ? [Number(value)] : Number(value),
});
records.should.eql([{ value: [1, 2, [3]] }]);
});

it("keeps empty arrays as individual cast values", function () {
const records = parseSync("1,2,3", {
columns: ["value", "value", "value"],
group_columns_by_name: true,
cast: () => [],
});
records.should.eql([{ value: [[], [], []] }]);
});
});