Skip to content

Commit 66d6f1d

Browse files
committed
feat(json): get full object when key is *
1 parent daf0e8e commit 66d6f1d

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,24 @@ const raffledValue = Json.raffle(array) // Raffled value from the array, could b
479479
console.log(raffledValue) // a, b or c
480480
```
481481

482+
```ts
483+
const object = {
484+
hello: {
485+
world: {
486+
value: {
487+
hello: 'Hello World!',
488+
},
489+
},
490+
},
491+
}
492+
493+
const value = Json.get(object, 'hello.world.value.hello') // 'Hello World!'
494+
const undefinedValue = Json.get(object, 'hello.worlld.value.hello') // undefined
495+
const defaultValue = Json.get(object, 'hello.worlld.value.hello', 'Hi World!') // 'Hi World!'
496+
const fullObject = Json.get(object, '*') // Same as object { hello: { world: { value: { hello: 'Hello World!' } } } }
497+
const defaultValueInObjectNull = Json.get(undefined, '*', { hello: 'world' }) // { hello: 'world' }
498+
```
499+
482500
---
483501

484502
### Module

src/Helpers/Json.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,10 @@ export class Json {
132132
* @return {any|undefined}
133133
*/
134134
static get(object, key, defaultValue) {
135+
if (key === '*' && object) {
136+
return object
137+
}
138+
135139
if (defaultValue) {
136140
return lodash.get(object, key, defaultValue)
137141
}

tests/Unit/JsonTest.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,13 @@ test.group('Json Class', () => {
108108
const value = Json.get(object, 'hello.world.value.hello')
109109
const undefinedValue = Json.get(object, 'hello.worlld.value.hello')
110110
const defaultValue = Json.get(object, 'hello.worlld.value.hello', 'Hi World!')
111+
const fullObject = Json.get(object, '*')
112+
const defaultValueInObjectNull = Json.get(undefined, '*', { hello: 'world' })
111113

112114
assert.equal(value, 'Hello World!')
113115
assert.equal(defaultValue, 'Hi World!')
114116
assert.isUndefined(undefinedValue)
117+
assert.deepEqual(object, fullObject)
118+
assert.deepEqual(defaultValueInObjectNull, { hello: 'world' })
115119
})
116120
})

0 commit comments

Comments
 (0)