We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 88b6eb6 commit a94ea95Copy full SHA for a94ea95
index.js
@@ -19,7 +19,7 @@ function getPathSegments(path) {
19
return parts;
20
}
21
22
-module.exports.get = (obj, path) => {
+module.exports.get = (obj, path, value) => {
23
if (!isObj(obj) || typeof path !== 'string') {
24
return obj;
25
@@ -28,7 +28,7 @@ module.exports.get = (obj, path) => {
28
29
for (let i = 0; i < pathArr.length; i++) {
30
if (!Object.prototype.propertyIsEnumerable.call(obj, pathArr[i])) {
31
- return;
+ return value;
32
33
34
obj = obj[pathArr[i]];
@@ -38,9 +38,9 @@ module.exports.get = (obj, path) => {
38
// if this is not the last bit of the path, and
39
// if it did't return `undefined`
40
// it would return `null` if `obj` is `null`
41
- // but we want `get({foo: null}, 'foo.bar')` to equal `undefined` not `null`
+ // but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied value, not `null`
42
if (i !== pathArr.length - 1) {
43
- return undefined;
44
45
46
break;
readme.md
@@ -22,6 +22,9 @@ dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');
dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep');
//=> undefined
+dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value');
26
+//=> 'default value'
27
+
dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot');
//=> 'unicorn'
@@ -54,7 +57,7 @@ console.log(obj);
54
57
55
58
## API
56
59
-### get(obj, path)
60
+### get(obj, path, [value])
61
62
### set(obj, path, value)
63
@@ -80,7 +83,7 @@ Use `\\.` if you have a `.` in the key.
80
83
81
84
Type: `any`
82
85
-Value to set at `path`.
86
+Value to set at `path` or optional default value to return from get.
87
88
89
## License
test.js
@@ -15,6 +15,7 @@ test('get', t => {
15
t.is(m.get({foo: {bar: {baz: null}}}, 'foo.bar.baz'), null);
16
t.is(m.get({foo: {bar: 'a'}}, 'foo.fake'), undefined);
17
t.is(m.get({foo: {bar: 'a'}}, 'foo.fake.fake2'), undefined);
18
+ t.is(m.get({foo: {bar: 'a'}}, 'foo.fake.fake2', 'some value'), 'some value');
t.is(m.get({'\\': true}, '\\'), true);
t.is(m.get({'\\foo': true}, '\\foo'), true);
t.is(m.get({'bar\\': true}, 'bar\\'), true);
@@ -40,6 +41,7 @@ test('get', t => {
const f3 = {foo: null};
t.is(m.get(f3, 'foo.bar'), undefined);
+ t.is(m.get(f3, 'foo.bar', 'some value'), 'some value');
t.is(m.get({'foo.baz': {bar: true}}, 'foo\\.baz.bar'), true);
47
t.is(m.get({'fo.ob.az': {bar: true}}, 'fo\\.ob\\.az.bar'), true);
0 commit comments