我有一个像这样的对象:
var myob= {
title: 'Hey',
list: [3, 74, 25],
myObject: {
myName: {
first: "Joe",
second: "Flynn"
}
}
我正在尝试通过括号表示法访问内部内容。
myob["title"] //works fine, returns 'Hey'
myob["list[0]"] //Doesn't work, returns undefined
myob["myObject[objectTitle]"] //Doesn't work, returns undefined
为什么这不起作用?有没有办法可以做到这一点,最好仍然在括号内使用相同的内容...?
链接到 jsfiddle:https://jsfiddle.net/j24dxpao/
最佳答案
对于这些基于字符串的嵌套对象访问,您可能想要使用像 lodash's get 这样的库。或等效的,因为它本身是不可能的。
const _ = require("lodash")
const schoolEvent = {
guests: [
{name: "John", handsome: true},
{name: "Ben", handsome: false}
]
}
_.get(schoolEvent, "guests[0].name") // "John"
关于javascript - JS 对象 : dot notation inside bracket notation, 列出了括号内的表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47204733/