Skip to content

Instantly share code, notes, and snippets.

@szanata
Created September 17, 2018 11:16
Show Gist options
  • Save szanata/ba4b9e33e4b918199bbfbf26ffe2a3b8 to your computer and use it in GitHub Desktop.
Save szanata/ba4b9e33e4b918199bbfbf26ffe2a3b8 to your computer and use it in GitHub Desktop.
Deep fetch properties on js objects, including array paths
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