Skip to content

Commit

Permalink
Fix unwind of nested fields
Browse files Browse the repository at this point in the history
  • Loading branch information
juanjoDiaz committed Feb 21, 2019
1 parent c910c35 commit b7c836f
Show file tree
Hide file tree
Showing 9 changed files with 298 additions and 3,477 deletions.
21 changes: 9 additions & 12 deletions lib/JSON2CSVBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@

const os = require('os');
const lodashGet = require('lodash.get');
const lodashSet = require('lodash.set');

const setProp = (obj, path, value) => {
const pathArray = Array.isArray(path) ? path : path.split('.');
const key = pathArray[0];
const newValue = pathArray.length > 1 ? setProp(obj[key] || {}, pathArray.slice(1), value) : value;
return Object.assign({}, obj, { [key]: newValue });
};

class JSON2CSVBase {
constructor(opts) {
Expand Down Expand Up @@ -255,15 +261,6 @@ class JSON2CSVBase {
*/
unwindData(dataRow, unwindPaths) {
const unwind = (rows, unwindPath) => {
const pathAndField = unwindPath.split(/\.(?=[^.]+$)/);
const setUnwoundValue = pathAndField.length === 2
? (() => {
const parentPath = pathAndField[0];
const unwindField = pathAndField[1];
return (row, value) => lodashSet(Object.assign({}, row), parentPath, Object.assign({}, lodashGet(row, parentPath), { [unwindField]: value }));
})()
: (row, value) => Object.assign({}, row, { [unwindPath]: value });

return rows
.map(row => {
const unwindArray = lodashGet(row, unwindPath);
Expand All @@ -273,15 +270,15 @@ class JSON2CSVBase {
}

if (!unwindArray.length) {
return setUnwoundValue(row, undefined);
return setProp(row, unwindPath, undefined);
}

return unwindArray.map((unwindRow, index) => {
const clonedRow = (this.opts.unwindBlank && index > 0)
? {}
: row;

return setUnwoundValue(clonedRow, unwindRow);
return setProp(clonedRow, unwindPath, unwindRow);
});
})
.reduce((a, e) => a.concat(e), []);
Expand Down
Loading

0 comments on commit b7c836f

Please sign in to comment.