From 5c55c65a86dd38e9bb91b88a69b9e85487dd0f27 Mon Sep 17 00:00:00 2001 From: Laurent Martelli Date: Sun, 22 Dec 2024 18:58:28 +0100 Subject: [PATCH] Fix getValue() It could not handle this case: { "key1": {"key3": "value1"}, "key1.key2": "value2" } --- projects/ngx-translate/src/lib/util.ts | 47 ++++++++++---------- projects/ngx-translate/src/lib/utils.spec.ts | 8 ++++ 2 files changed, 32 insertions(+), 23 deletions(-) diff --git a/projects/ngx-translate/src/lib/util.ts b/projects/ngx-translate/src/lib/util.ts index fa5ae22..fe9e467 100644 --- a/projects/ngx-translate/src/lib/util.ts +++ b/projects/ngx-translate/src/lib/util.ts @@ -107,32 +107,33 @@ export function mergeDeep(target: any, source: any): any { * @param target * @param key */ -export function getValue(target: any, key: string): any -{ - const keys = key.split("."); - - key = ""; - do - { - key += keys.shift(); - if (isDefined(target) && isDefined(target[key]) && (isDict(target[key]) ||isArray(target[key]) || !keys.length)) - { - target = target[key]; - key = ""; - } - else if (!keys.length) - { - target = undefined; - } - else - { - key += "."; - } - } while (keys.length); - +export function getValue(target: any, key: string) { + let keys = key.split("."); + let matchedKey: string|undefined = key; + while(keys.length) { + [matchedKey, keys] = getLongestMatchingSubKey(target,keys); + if (matchedKey===undefined) + return undefined; + target = target[matchedKey]; + } return target; } +function getLongestMatchingSubKey(target: any, keys: string[]): [string|undefined, string[]] { + let key = ''; + let matchedKey; + let size; + for (let i=0; i {a:{b:{c: "test2"}}} diff --git a/projects/ngx-translate/src/lib/utils.spec.ts b/projects/ngx-translate/src/lib/utils.spec.ts index d3c4c7d..900e06a 100644 --- a/projects/ngx-translate/src/lib/utils.spec.ts +++ b/projects/ngx-translate/src/lib/utils.spec.ts @@ -226,6 +226,14 @@ describe("Utils", () => 'key1': "value1", 'key1.key2': "value2" }, 'key1.key2')).toEqual("value2"); + expect(getValue({ + 'key1': {'key3': "value1"}, + 'key1.key2': "value2" + }, 'key1.key2')).toEqual("value2"); + expect(getValue({ + 'key1': ["a","b","c"], + 'key1.key2': "value2" + }, 'key1.key2')).toEqual("value2"); expect(getValue({'key1.key2': {key3: "value3"}}, 'key1.key2')).toEqual({key3: "value3"}); });