Skip to content

Commit 2d69281

Browse files
juanjoDiazknownasilya
authored andcommitted
fix: unwind of nested fields (#357)
1 parent c910c35 commit 2d69281

File tree

9 files changed

+298
-3477
lines changed

9 files changed

+298
-3477
lines changed

lib/JSON2CSVBase.js

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@
22

33
const os = require('os');
44
const lodashGet = require('lodash.get');
5-
const lodashSet = require('lodash.set');
5+
6+
const setProp = (obj, path, value) => {
7+
const pathArray = Array.isArray(path) ? path : path.split('.');
8+
const key = pathArray[0];
9+
const newValue = pathArray.length > 1 ? setProp(obj[key] || {}, pathArray.slice(1), value) : value;
10+
return Object.assign({}, obj, { [key]: newValue });
11+
};
612

713
class JSON2CSVBase {
814
constructor(opts) {
@@ -255,15 +261,6 @@ class JSON2CSVBase {
255261
*/
256262
unwindData(dataRow, unwindPaths) {
257263
const unwind = (rows, unwindPath) => {
258-
const pathAndField = unwindPath.split(/\.(?=[^.]+$)/);
259-
const setUnwoundValue = pathAndField.length === 2
260-
? (() => {
261-
const parentPath = pathAndField[0];
262-
const unwindField = pathAndField[1];
263-
return (row, value) => lodashSet(Object.assign({}, row), parentPath, Object.assign({}, lodashGet(row, parentPath), { [unwindField]: value }));
264-
})()
265-
: (row, value) => Object.assign({}, row, { [unwindPath]: value });
266-
267264
return rows
268265
.map(row => {
269266
const unwindArray = lodashGet(row, unwindPath);
@@ -273,15 +270,15 @@ class JSON2CSVBase {
273270
}
274271

275272
if (!unwindArray.length) {
276-
return setUnwoundValue(row, undefined);
273+
return setProp(row, unwindPath, undefined);
277274
}
278275

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

284-
return setUnwoundValue(clonedRow, unwindRow);
281+
return setProp(clonedRow, unwindPath, unwindRow);
285282
});
286283
})
287284
.reduce((a, e) => a.concat(e), []);

0 commit comments

Comments
 (0)