From a94ea95d225a64d7e84e037f487a38e2f336a2ca Mon Sep 17 00:00:00 2001 From: Michael Novotny Date: Sun, 4 Sep 2016 11:15:15 -0500 Subject: [PATCH] Add ability to return default value if path is undefined (#31) --- index.js | 8 ++++---- readme.md | 7 +++++-- test.js | 2 ++ 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 8e3dded..2748b23 100644 --- a/index.js +++ b/index.js @@ -19,7 +19,7 @@ function getPathSegments(path) { return parts; } -module.exports.get = (obj, path) => { +module.exports.get = (obj, path, value) => { if (!isObj(obj) || typeof path !== 'string') { return obj; } @@ -28,7 +28,7 @@ module.exports.get = (obj, path) => { for (let i = 0; i < pathArr.length; i++) { if (!Object.prototype.propertyIsEnumerable.call(obj, pathArr[i])) { - return; + return value; } obj = obj[pathArr[i]]; @@ -38,9 +38,9 @@ module.exports.get = (obj, path) => { // if this is not the last bit of the path, and // if it did't return `undefined` // it would return `null` if `obj` is `null` - // 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` if (i !== pathArr.length - 1) { - return undefined; + return value; } break; diff --git a/readme.md b/readme.md index 5f2d37c..3d5cfb9 100644 --- a/readme.md +++ b/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'); +//=> 'default value' + dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot'); //=> 'unicorn' @@ -54,7 +57,7 @@ console.log(obj); ## API -### get(obj, path) +### get(obj, path, [value]) ### set(obj, path, value) @@ -80,7 +83,7 @@ Use `\\.` if you have a `.` in the key. Type: `any` -Value to set at `path`. +Value to set at `path` or optional default value to return from get. ## License diff --git a/test.js b/test.js index 46e104d..46f1291 100644 --- a/test.js +++ b/test.js @@ -15,6 +15,7 @@ test('get', t => { t.is(m.get({foo: {bar: {baz: null}}}, 'foo.bar.baz'), null); t.is(m.get({foo: {bar: 'a'}}, 'foo.fake'), undefined); t.is(m.get({foo: {bar: 'a'}}, 'foo.fake.fake2'), undefined); + 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); t.is(m.get({'fo.ob.az': {bar: true}}, 'fo\\.ob\\.az.bar'), true);