Created
September 17, 2018 11:16
-
-
Save szanata/ba4b9e33e4b918199bbfbf26ffe2a3b8 to your computer and use it in GitHub Desktop.
Deep fetch properties on js objects, including array paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepFetch( object, path ) { | |
return path.split( '.' ).reduce( ( value, part ) => { | |
if ( Array.isArray( value ) ) { | |
return value.reduce( (arr, v) => arr.concat( deepFetch( v, part ) ), [] ); | |
} else if ( part === '*' ) { | |
return Object.keys( value ).map( p => value[p] ); | |
} | |
return value[part]; | |
}, object ); | |
} | |
const easyObject = { foo: { bar: 'my secret value' } }; | |
const arrayObject = { | |
foo: [ | |
{ '0': { bar: 'my secret value' } }, | |
{ 'x': { bar: 'my other secret' } } | |
] | |
}; | |
console.assert( deepStartSix( superComplexObj, 'foo.*.bar' ), 'my secret value' ); | |
console.assert( deepStartSix( easyObject, 'foo.bar' ), 'my secret value' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment