function getObjectDataByKey( field, theObject ){ // get data return field.split('.').reduce((o,i)=> o[i], theObject); } // a simple object const myObject = { name: 'John', lastname: 'Doe', data: { birthDate: '01/01/1970', placeOfBirth: 'San Francisco' } } // variable representing a key of the object const field = 'data.birthDate'; console.log ( getObjectDataByKey ( field , myObject ) ); //will print //01/01/1970 // also simple key will return correct value console.log ( getObjectDataByKey ( 'name' , myObject) ); //will print //John
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter