From 0201dc74d774e54864c1e05b07d1fc624cec3819 Mon Sep 17 00:00:00 2001 From: Ivan Eisenberg Date: Tue, 10 Mar 2020 10:18:44 -0500 Subject: [PATCH] support array lookup syntax, better test coverage --- src/private/get.js | 11 +++++++++-- src/private/get.spec.js | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/private/get.js b/src/private/get.js index 74eca4c..9355137 100644 --- a/src/private/get.js +++ b/src/private/get.js @@ -1,10 +1,17 @@ -const get = (object, keys = '') => { +const get = (object, keys) => { if (!object) { object = {} } - keys = Array.isArray(keys) ? keys : keys.replace(/\[(['"]?)([\w\d-]+)(['"]?)\]/g, '.$2').split('.') + + keys = Array.isArray(keys) ? keys : `${keys}` + .replace(/\[['"]?([\w\d-]+)['"]?\]/g, '.$1') + .split('.') + .filter(x => x) + object = object[keys[0]] + if (object && keys.length > 1) { return get(object, keys.slice(1)) } + return object } diff --git a/src/private/get.spec.js b/src/private/get.spec.js index e2e633b..8f9de02 100644 --- a/src/private/get.spec.js +++ b/src/private/get.spec.js @@ -62,6 +62,32 @@ describe('get', () => { expect(actual).toEqual(expected) }) + it('should return undefined if not provided a selector', () => { + const data = { + foo: { 'ba-ar': 'bars' } + } + const actual = get(data) + const expected = undefined + + expect(actual).toEqual(expected) + }) + + it('should allow lookups in arrays', () => { + const greenArr = [ + '[1]', + '1', + 1 + ] + + const data = ['foo', 'bar'] + const expected = 'bar' + + greenArr.forEach((x) => { + const actual = get(data, x) + expect(actual).toEqual(expected) + }) + }) + it('should return undefined when called with bad data', () => { const redArr = [ undefined,