Skip to content

Commit 3ad1810

Browse files
author
Duncan Rance
authored
Merge pull request #148 from gpittarelli/147-toApiFormat-preserve-structure
Preserve array/object structure of API data
2 parents b4a603c + d6ae5b9 commit 3ad1810

File tree

2 files changed

+31
-12
lines changed

2 files changed

+31
-12
lines changed

lib/toApiFormat.js

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,11 @@ var excludeList = [
1212
];
1313

1414
function snakedKeyClone(source) {
15-
1615
if (!_.isObject(source)) {
1716
return source;
1817
}
1918

20-
var target = {};
21-
22-
if (Array.isArray(source)) {
23-
target = [];
24-
for (var i = 0; i < source.length; i++) {
25-
target.push(snakedKeyClone(source[i]));
26-
}
27-
return target;
28-
}
19+
var target = Array.isArray(source) ? [] : {};
2920

3021
Object.keys(source).forEach(function(key) {
3122
target[_.snakeCase(key)] = snakedKeyClone(source[key]);
@@ -51,8 +42,10 @@ module.exports = function toApiFormat(source) {
5142
var target = snakedKeyClone(source);
5243

5344
// Reinstated the un-modified objects into the target
54-
pointer.walk(excludedObjects, function(val, ptr) {
55-
pointer.set(target, ptr, val);
45+
excludeList.forEach(function(exclusionPointer) {
46+
if (pointer.has(excludedObjects, exclusionPointer)) {
47+
pointer.set(target, exclusionPointer, pointer.get(excludedObjects, exclusionPointer));
48+
}
5649
});
5750

5851
return target;

test/spec/toApiFormat.spec.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,4 +155,30 @@ describe('toApiFormat', function() {
155155

156156
done();
157157
});
158+
159+
it('should preserve objects with number properties', function(done) {
160+
var testObj = {
161+
array: [ 0, 1, , , , 5, 6]
162+
, object: {
163+
"0": 0,
164+
"1": 1,
165+
"5": 5,
166+
"6": 6
167+
}
168+
, substitution_data: {
169+
"0": 0,
170+
"1": 1,
171+
"5": 5,
172+
"6": 6
173+
}
174+
, tags: [ 0, 1, , , , 5, 6]
175+
};
176+
177+
178+
var out = toApiFormat(_.clone(testObj));
179+
180+
expect(out).to.deep.equal(testObj);
181+
182+
done();
183+
});
158184
});

0 commit comments

Comments
 (0)