Skip to content

Commit ebad031

Browse files
Merge pull request #515 from anthonygood/fix/by-dot
Ensure `existsByDot` and `getByDot` honour properties with dots in keys
2 parents 4140353 + 2d0e33c commit ebad031

File tree

4 files changed

+18
-2
lines changed

4 files changed

+18
-2
lines changed

lib/common/exists-by-dot.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11

22
module.exports = function (obj, path) {
3+
if (path in obj) return true;
4+
35
const parts = path.split('.');
46
const nonLeafLen = parts.length - 1;
57

lib/common/get-by-dot.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
module.exports = function (obj, path) {
33
if (typeof obj !== 'object' || obj === null) return undefined;
44

5-
if (path.indexOf('.') === -1) {
5+
if (path.indexOf('.') === -1 || path in obj) {
66
return obj[path];
77
}
88

tests/services/exists-by-dot.test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,15 @@ describe('test existsByDot', () => {
4242
assert.equal(existsByDot({}, 'name'), false);
4343
});
4444

45+
it('finds property with dot in key', () => {
46+
const obj = { 'name.first': 'John' };
47+
assert.equal(existsByDot(obj, 'name.first'), true);
48+
assert.equal(existsByDot(obj, 'name'), false);
49+
assert.equal(existsByDot(obj, 'first'), false);
50+
assert.equal(existsByDot(obj, 'namefirst'), false);
51+
assert.equal(existsByDot(obj, 'name.first.foo'), false);
52+
});
53+
4554
it('does not throw if path ends prematurely', () => {
4655
assert.deepEqual(existsByDot(obj, 'x'), false);
4756
assert.deepEqual(existsByDot(obj, 'name.a.c.x'), false);

tests/services/get-set-by-dot.test.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ describe('services byDot', () => {
2222
name: 'John',
2323
address: { line1: '100 5-th Avenue', city: 'New York' }
2424
}
25-
}
25+
},
26+
'foo.bar': {}
2627
};
2728
});
2829

@@ -47,6 +48,10 @@ describe('services byDot', () => {
4748
obj.manager.employee.address.city);
4849
});
4950

51+
it('gets top level property with dot in key', () => {
52+
assert.equal(getByDot(obj, 'foo.bar'), obj['foo.bar']);
53+
});
54+
5055
it('does not throw on missing path, at top', () => {
5156
assert.equal(getByDot(obj, 'xxx'), undefined);
5257
});

0 commit comments

Comments
 (0)