Skip to content

Commit e435322

Browse files
committed
camelising nested attributes
1 parent b54ba32 commit e435322

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

src/normalize.js

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,20 @@ function extractRelationships(relationships, { camelizeKeys }) {
4242
return ret;
4343
}
4444

45+
function camelizeNestedKeys(attributeValue) {
46+
if (attributeValue === null || typeof attributeValue !== 'object') {
47+
return attributeValue;
48+
}
49+
50+
const copy = {};
51+
52+
keys(attributeValue).forEach((k) => {
53+
copy[camelCase(k)] = camelizeNestedKeys(attributeValue[k]);
54+
});
55+
56+
return copy;
57+
}
58+
4559
function extractEntities(json, { camelizeKeys }) {
4660
const ret = {};
4761

@@ -57,7 +71,7 @@ function extractEntities(json, { camelizeKeys }) {
5771
ret[type][elem.id].attributes = {};
5872

5973
keys(elem.attributes).forEach((key) => {
60-
ret[type][elem.id].attributes[camelCase(key)] = elem.attributes[key];
74+
ret[type][elem.id].attributes[camelCase(key)] = camelizeNestedKeys(elem.attributes[key]);
6175
});
6276
} else {
6377
ret[type][elem.id].attributes = elem.attributes;
@@ -75,7 +89,7 @@ function extractEntities(json, { camelizeKeys }) {
7589
ret[type][elem.id].relationships =
7690
extractRelationships(elem.relationships, { camelizeKeys });
7791
}
78-
92+
7993
if (elem.meta) {
8094
ret[type][elem.id].meta = elem.meta;
8195
}

test/normalize.spec.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,37 @@ describe('data is normalized', () => {
9797

9898
expect(isEqual(normalize(input), camelizedOutput)).to.be.true;
9999
});
100+
101+
it('nested keys camelized', () => {
102+
const input = {
103+
data: [{
104+
type: 'post',
105+
id: 1,
106+
attributes: {
107+
key_is_camelized: 2,
108+
another_key: {
109+
and_yet_another: 3
110+
}
111+
}
112+
}]
113+
};
114+
115+
const camelizedOutput = {
116+
post: {
117+
"1": {
118+
id: 1,
119+
attributes: {
120+
keyIsCamelized: 2,
121+
anotherKey: {
122+
andYetAnother: 3
123+
}
124+
}
125+
}
126+
}
127+
};
128+
129+
expect(isEqual(normalize(input), camelizedOutput)).to.be.true;
130+
});
100131
});
101132

102133
describe('included is normalized', () => {

0 commit comments

Comments
 (0)