Skip to content

Commit

Permalink
feat(json): get full object when key is *
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Sep 7, 2022
1 parent daf0e8e commit 66d6f1d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/Helpers/Json.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
4 changes: 4 additions & 0 deletions tests/Unit/JsonTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' })
})
})

0 comments on commit 66d6f1d

Please sign in to comment.