Skip to content

Commit 6e4ea5e

Browse files
authored
fix: don't mutate original object in unset (#499)
1 parent b071eb1 commit 6e4ea5e

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lib/utils.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@ function unsetProp(obj, path) {
2222
}
2323

2424
if (pathArray.length === 1) {
25-
delete obj[key];
26-
return obj;
25+
return Object.keys(obj)
26+
.filter(prop => prop !== key)
27+
.reduce((acc, prop) => Object.assign(acc, { [prop]: obj[prop] }), {});
2728
}
2829

2930
return unsetProp(obj[key], restPath);

test/JSON2CSVParser.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,21 @@ module.exports = (testRunner, jsonFixtures, csvFixtures) => {
2525
t.end();
2626
});
2727

28+
testRunner.add('should not modify the JSON object passed passed', (t) => {
29+
const opts = {
30+
fields: ["carModel", "price", "extras.items.name", "extras.items.items.position", "extras.items.items.color", "extras.items.items", "name", "color", "extras.items.color"],
31+
transforms: [unwind({ paths: ['extras.items', 'extras.items.items'] }), flatten()],
32+
};
33+
const parser = new Json2csvParser(opts);
34+
const originalJson = JSON.parse(JSON.stringify(jsonFixtures.unwindComplexObject));
35+
const csv = parser.parse(originalJson);
36+
37+
t.ok(typeof csv === 'string');
38+
t.equal(csv, csvFixtures.unwindComplexObject);
39+
t.deepEqual(jsonFixtures.unwindComplexObject, originalJson);
40+
t.end();
41+
});
42+
2843
testRunner.add('should error if input data is not an object', (t) => {
2944
const input = 'not an object';
3045
try {

0 commit comments

Comments
 (0)