File tree Expand file tree Collapse file tree 2 files changed +35
-10
lines changed Expand file tree Collapse file tree 2 files changed +35
-10
lines changed Original file line number Diff line number Diff line change @@ -2,32 +2,28 @@ import isObject from './is-object';
22import Err from '../-private/err' ;
33import { PublicErrors } from '../types' ;
44
5- let keysUpToValue : string [ ] = [ ] ;
6-
75/**
86 * traverse through target and return leaf nodes with `value` property and key as 'person.name'
97 *
108 * @method getKeyValues
119 * @return {Array } [{ 'person.name': value }]
1210 */
13- export function getKeyValues < T extends Record < string , any > > ( obj : T ) : Record < string , any > [ ] {
11+ export function getKeyValues < T extends Record < string , any > > (
12+ obj : T ,
13+ keysUpToValue : Array < string > = [ ]
14+ ) : Record < string , any > [ ] {
1415 const map = [ ] ;
1516
1617 for ( let key in obj ) {
17- keysUpToValue . push ( key ) ;
18-
1918 if ( obj [ key ] && isObject ( obj [ key ] ) ) {
2019 if ( Object . prototype . hasOwnProperty . call ( obj [ key ] , 'value' ) ) {
21- map . push ( { key : keysUpToValue . join ( '.' ) , value : obj [ key ] . value } ) ;
22- // stop collecting keys
23- keysUpToValue = [ ] ;
20+ map . push ( { key : [ ...keysUpToValue , key ] . join ( '.' ) , value : obj [ key ] . value } ) ;
2421 } else if ( key !== 'value' ) {
25- map . push ( ...getKeyValues ( obj [ key ] ) ) ;
22+ map . push ( ...getKeyValues ( obj [ key ] , [ ... keysUpToValue , key ] ) ) ;
2623 }
2724 }
2825 }
2926
30- keysUpToValue = [ ] ;
3127 return map ;
3228}
3329
Original file line number Diff line number Diff line change 1+ import { getKeyValues } from '../../src/utils/get-key-values' ;
2+
3+ describe ( 'Unit | Utility | getKeyValues' , function ( ) {
4+ it ( 'it works with single level values' , ( ) => {
5+ const result = getKeyValues ( { test : { value : 1 } } ) ;
6+
7+ expect ( result ) . toEqual ( [ { key : 'test' , value : 1 } ] ) ;
8+ } ) ;
9+
10+ it ( 'it works with nested keys' , ( ) => {
11+ const result = getKeyValues ( {
12+ user : {
13+ firstName : { value : 'Michael' } ,
14+ lastName : { value : 'Bolton' } ,
15+ address : {
16+ city : { value : 'NYC' } ,
17+ state : { value : 'New York' }
18+ }
19+ }
20+ } ) ;
21+
22+ expect ( result ) . toEqual ( [
23+ { key : 'user.firstName' , value : 'Michael' } ,
24+ { key : 'user.lastName' , value : 'Bolton' } ,
25+ { key : 'user.address.city' , value : 'NYC' } ,
26+ { key : 'user.address.state' , value : 'New York' }
27+ ] ) ;
28+ } ) ;
29+ } ) ;
You can’t perform that action at this time.
0 commit comments