From 587da5c96be12a76a94c5f8f890f1fe329dbe236 Mon Sep 17 00:00:00 2001 From: Sergey Astapov Date: Tue, 24 Mar 2020 22:50:50 -0400 Subject: [PATCH] Fixed changes getter --- src/utils/get-key-values.ts | 16 ++++++---------- test/utils/get-key-values.test.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 10 deletions(-) create mode 100644 test/utils/get-key-values.test.ts diff --git a/src/utils/get-key-values.ts b/src/utils/get-key-values.ts index 8a4626e..570cade 100644 --- a/src/utils/get-key-values.ts +++ b/src/utils/get-key-values.ts @@ -2,32 +2,28 @@ import isObject from './is-object'; import Err from '../-private/err'; import { PublicErrors } from '../types'; -let keysUpToValue: string[] = []; - /** * traverse through target and return leaf nodes with `value` property and key as 'person.name' * * @method getKeyValues * @return {Array} [{ 'person.name': value }] */ -export function getKeyValues>(obj: T): Record[] { +export function getKeyValues>( + obj: T, + keysUpToValue: Array = [] +): Record[] { const map = []; for (let key in obj) { - keysUpToValue.push(key); - if (obj[key] && isObject(obj[key])) { if (Object.prototype.hasOwnProperty.call(obj[key], 'value')) { - map.push({ key: keysUpToValue.join('.'), value: obj[key].value }); - // stop collecting keys - keysUpToValue = []; + map.push({ key: [...keysUpToValue, key].join('.'), value: obj[key].value }); } else if (key !== 'value') { - map.push(...getKeyValues(obj[key])); + map.push(...getKeyValues(obj[key], [...keysUpToValue, key])); } } } - keysUpToValue = []; return map; } diff --git a/test/utils/get-key-values.test.ts b/test/utils/get-key-values.test.ts new file mode 100644 index 0000000..e0f7cbf --- /dev/null +++ b/test/utils/get-key-values.test.ts @@ -0,0 +1,29 @@ +import { getKeyValues } from '../../src/utils/get-key-values'; + +describe('Unit | Utility | getKeyValues', function() { + it('it works with single level values', () => { + const result = getKeyValues({ test: { value: 1 } }); + + expect(result).toEqual([{ key: 'test', value: 1 }]); + }); + + it('it works with nested keys', () => { + const result = getKeyValues({ + user: { + firstName: { value: 'Michael' }, + lastName: { value: 'Bolton' }, + address: { + city: { value: 'NYC' }, + state: { value: 'New York' } + } + } + }); + + expect(result).toEqual([ + { key: 'user.firstName', value: 'Michael' }, + { key: 'user.lastName', value: 'Bolton' }, + { key: 'user.address.city', value: 'NYC' }, + { key: 'user.address.state', value: 'New York' } + ]); + }); +});