Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed changes getter #25

Merged
merged 1 commit into from
Mar 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions src/utils/get-key-values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends Record<string, any>>(obj: T): Record<string, any>[] {
export function getKeyValues<T extends Record<string, any>>(
obj: T,
keysUpToValue: Array<string> = []
): Record<string, any>[] {
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;
}

Expand Down
29 changes: 29 additions & 0 deletions test/utils/get-key-values.test.ts
Original file line number Diff line number Diff line change
@@ -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' }
]);
});
});