从字符串数组创建括号符号



我有一个像这样的字符串数组:

const deepProperties = ['contactPerson', 'firstName']

如何访问具有此字符串数组的匿名对象的属性contactPerson.firstName(get和set) ?

const unknown = { contactPerson: { firstName: 'Jane' } }

我知道我可以做unknown['contactPerson']['firstName']来获得值和unknown['contactPerson']['firstName'] = 'John'来设置一个新值-但是我如何从数组中得到那里?

可以使用lodash get/set。

例如:

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' } }
注意,如果嵌入的属性包含数组,这也可以工作,例如:
const props = ["users[1]", "name"];
const org = { users:[{name:"joe",age:21}, {name:"mary",age:29}] };
get(org, props.join("."));
// 'mary'

最新更新