diff --git a/package-lock.json b/package-lock.json index f759b18..9c70532 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@athenna/common", - "version": "5.22.0", + "version": "5.23.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@athenna/common", - "version": "5.22.0", + "version": "5.23.0", "license": "MIT", "dependencies": { "@fastify/formbody": "^8.0.2", diff --git a/package.json b/package.json index 14ac3c4..b103f19 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@athenna/common", - "version": "5.22.0", + "version": "5.23.0", "description": "The Athenna common helpers to use in any Node.js ESM project.", "license": "MIT", "author": "João Lenon ", diff --git a/src/helpers/Json.ts b/src/helpers/Json.ts index f0c38ca..b964c7b 100644 --- a/src/helpers/Json.ts +++ b/src/helpers/Json.ts @@ -421,6 +421,17 @@ export class Json { return lodash.get(object, key, defaultValue) } + /** + * Set the object values based on a key. + */ + public static set(object: T, key: string, value: any): T { + if (key === '' && object) { + return object + } + + return lodash.set(object as unknown as any, key, value) + } + /** * Sort an object or an array of objects by it keys names. */ diff --git a/tests/unit/helpers/JsonTest.ts b/tests/unit/helpers/JsonTest.ts index 5d14d12..702bc80 100644 --- a/tests/unit/helpers/JsonTest.ts +++ b/tests/unit/helpers/JsonTest.ts @@ -185,6 +185,32 @@ export default class JsonTest { assert.deepEqual(falsyDefaultValue, false) } + @Test() + public async shouldBeAbleToSetNestedPropertiesInsideAnObject({ assert }: Context) { + const object = {} + + const newObject = Json.set(object, 'hello.world.value.hello', 'Hello World!') + + assert.deepEqual(object, { + hello: { + world: { + value: { + hello: 'Hello World!' + } + } + } + }) + assert.deepEqual(newObject, { + hello: { + world: { + value: { + hello: 'Hello World!' + } + } + } + }) + } + @Test() public async shouldBeAbleToSortObjects({ assert }: Context) { const object = {