0

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?

Yash Jani
  • 154
  • 1
  • 13
Alexander Zeitler
  • 11,919
  • 11
  • 81
  • 124
  • `deepProperties.reduce((p, c) => p[c], unknown);`, potentially with optional chaining, if there is a chance it doesn't exist. – ASDFGerte Oct 04 '21 at 13:20
  • Any reason not to use: `unknown[deepProperties[0]][deepProperties[1]]`? – jarmod Oct 04 '21 at 13:24
  • @jarmod the number of strings in the array is dynamic. – Alexander Zeitler Oct 04 '21 at 13:25
  • Perhaps lodash get/set would work for you ([examples](https://www.penta-code.com/lodash-get-and-set/)). You'd have to join the property names, for example: `deepProperties.join(".")` to create the relevant hierarchical property path. – jarmod Oct 04 '21 at 13:32

1 Answers1

1

You can use lodash get/set.

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'
jarmod
  • 71,565
  • 16
  • 115
  • 122