Use reduce() to get object value by key name set as dotted variable
Mon Jun 27 2022 06:19:23 GMT+0000 (Coordinated Universal Time)
Saved by
@swina
#javascript
#reduce
#object
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
content_copyCOPY
When you need to map an object with fields defined by a configuration variable.
Comments