Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign up`json_to_sheet` mutates header array #2139
Comments
@paustint Suppose there were two missing fields: const data = [
{f1: 1, f2: 2, f3: 3, f4: 4}
];
const header = ['f1', 'f2']; When the sheet is written, both f3 and f4 will be written after f1 and f2. The order is dependent on the order of presentation within the data itself. For example: const data = [
{f1: 1, f4: 4},
{f2: 2, f3: 3},
]; The order will start with const data = [
{f2: 2, f3: 3},
{f1: 1, f4: 4},
]; the write order will be We needed a way to communicate that ordering back to the caller. Since elements are never removed (they are only appended if data objects have headers that are missing), mutating the array preserves the intent and lets you chain into subsequent calls of const header = ['f1', 'f2'];
const worksheet = XLSX.utils.json_to_sheet([
{f2: 2, f3: 3},
], {header});
XLSX.utils.sheet_add_json(worksheet, [
{f1: 1, f4: 4},
], {header, origin: -1, skipHeader: true}); |
I understand. Many libraries will ignore extra headers if they are not included in the first row of data if a headers array not explicitly specified and I think that sheetsjs has the better approach of not requiring all rows to be the exact same shape. I now understand the tradeoffs much better, thank you for taking the time to explain. |
Now that you understand this, maybe you can help improve the docs :) We'll accept a PR that clarifies the behavior. |
I am experiencing the same problem.
In addition, sheets js is mutating the header array passed in, which is not something I would ever expect.
Example:
Originally posted by @paustint in #1487 (comment)