diff --git a/README.md b/README.md index aea3337..aeb69ac 100644 --- a/README.md +++ b/README.md @@ -479,6 +479,24 @@ const raffledValue = Json.raffle(array) // Raffled value from the array, could b console.log(raffledValue) // a, b or c ``` +```ts +const object = { + hello: { + world: { + value: { + hello: 'Hello World!', + }, + }, + }, +} + +const value = Json.get(object, 'hello.world.value.hello') // 'Hello World!' +const undefinedValue = Json.get(object, 'hello.worlld.value.hello') // undefined +const defaultValue = Json.get(object, 'hello.worlld.value.hello', 'Hi World!') // 'Hi World!' +const fullObject = Json.get(object, '*') // Same as object { hello: { world: { value: { hello: 'Hello World!' } } } } +const defaultValueInObjectNull = Json.get(undefined, '*', { hello: 'world' }) // { hello: 'world' } +``` + --- ### Module diff --git a/src/Helpers/Json.js b/src/Helpers/Json.js index 4f9aed5..d34a46d 100644 --- a/src/Helpers/Json.js +++ b/src/Helpers/Json.js @@ -132,6 +132,10 @@ export class Json { * @return {any|undefined} */ static get(object, key, defaultValue) { + if (key === '*' && object) { + return object + } + if (defaultValue) { return lodash.get(object, key, defaultValue) } diff --git a/tests/Unit/JsonTest.js b/tests/Unit/JsonTest.js index ea582fa..9ba784c 100644 --- a/tests/Unit/JsonTest.js +++ b/tests/Unit/JsonTest.js @@ -108,9 +108,13 @@ test.group('Json Class', () => { const value = Json.get(object, 'hello.world.value.hello') const undefinedValue = Json.get(object, 'hello.worlld.value.hello') const defaultValue = Json.get(object, 'hello.worlld.value.hello', 'Hi World!') + const fullObject = Json.get(object, '*') + const defaultValueInObjectNull = Json.get(undefined, '*', { hello: 'world' }) assert.equal(value, 'Hello World!') assert.equal(defaultValue, 'Hi World!') assert.isUndefined(undefinedValue) + assert.deepEqual(object, fullObject) + assert.deepEqual(defaultValueInObjectNull, { hello: 'world' }) }) })