I have an array of strings like this:
const deepProperties = ['contactPerson', 'firstName']
How can access the property contactPerson.firstName
(get and set) of an anonymous object having this string array at hand?
const unknown = { contactPerson: { firstName: 'Jane' } }
I know I can do unknown['contactPerson']['firstName']
to get the value and unknown['contactPerson']['firstName'] = 'John'
to set a new value - but how do I get there from the array?
For example:
const get = require('lodash.get');
const set = require('lodash.set');
const deepProperties = ['contactPerson', 'firstName']
const unknown = { contactPerson: { firstName: 'Jane' } }
get(unknown, deepProperties.join("."))
// 'Jane'
set(unknown, deepProperties.join("."), "Mary")
// { contactPerson: { firstName: 'Mary' } }
Note that this would also work if the embedded properties included arrays, for example:
const props = ["users[1]", "name"];
const org = { users:[{name:"joe",age:21}, {name:"mary",age:29}] };
get(org, props.join("."));
// 'mary'