Skip to content

Commit deeb74b

Browse files
committed
feat(json): add set method
1 parent a232312 commit deeb74b

File tree

4 files changed

+40
-3
lines changed

4 files changed

+40
-3
lines changed

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@athenna/common",
3-
"version": "5.22.0",
3+
"version": "5.23.0",
44
"description": "The Athenna common helpers to use in any Node.js ESM project.",
55
"license": "MIT",
66
"author": "João Lenon <lenon@athenna.io>",

src/helpers/Json.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,17 @@ export class Json {
421421
return lodash.get(object, key, defaultValue)
422422
}
423423

424+
/**
425+
* Set the object values based on a key.
426+
*/
427+
public static set<T = any>(object: T, key: string, value: any): T {
428+
if (key === '' && object) {
429+
return object
430+
}
431+
432+
return lodash.set<T>(object as unknown as any, key, value)
433+
}
434+
424435
/**
425436
* Sort an object or an array of objects by it keys names.
426437
*/

tests/unit/helpers/JsonTest.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,32 @@ export default class JsonTest {
185185
assert.deepEqual(falsyDefaultValue, false)
186186
}
187187

188+
@Test()
189+
public async shouldBeAbleToSetNestedPropertiesInsideAnObject({ assert }: Context) {
190+
const object = {}
191+
192+
const newObject = Json.set(object, 'hello.world.value.hello', 'Hello World!')
193+
194+
assert.deepEqual(object, {
195+
hello: {
196+
world: {
197+
value: {
198+
hello: 'Hello World!'
199+
}
200+
}
201+
}
202+
})
203+
assert.deepEqual(newObject, {
204+
hello: {
205+
world: {
206+
value: {
207+
hello: 'Hello World!'
208+
}
209+
}
210+
}
211+
})
212+
}
213+
188214
@Test()
189215
public async shouldBeAbleToSortObjects({ assert }: Context) {
190216
const object = {

0 commit comments

Comments
 (0)