首页 > 解决方案 > 无法访问对象内的键

问题描述

我正在尝试访问 Javascript 对象内的键的值。我的对象目前看起来像:

const options = {
  "account.country": getCountry,
  "account.phone": getPhone,
}

当 I 时console.log(options),它显示整个对象。但是,当我尝试

console.log(options.account) // undefined, 
console.log(options.account.country) // error. 

我不明白为什么。我也试过:

 const parsedObj = JSON.parse(options);
 console.log(parsedObj);

但它只是返回

'位置 1 的 JSON 中的意外标记 o'

标签: javascriptobject

解决方案


当您想从字符串访问属性时,您应该使用括号表示法。

const options = {
  "account.country": 'getCountry',
  "account.phone": 'getPhone',
}
console.log(options['account.country'])


推荐阅读