有没有一种简单的方法可以使用字符串形式的嵌套对象>数组键?

Is there an easy way to use nested object > array key in string form?

我拥有的是某种对象,我事先不知道其结构,而且我还收到了我需要的某个值的键(以字符串形式),它包含在该对象中。当我需要的值嵌套在数组中时,问题就出现了。


let someObject = {
  nonProblematicValue: "all good",
  arrayOfValues: ["can't touch this"]
}
let keyThatWorks = "nonProblematicValue";
let keyThatDoesNotWork = "arrayOfValues[0]"

我试过了

someObject[keyThatDoesNotWork] //undefined
someObject.[keyThatDoesNotWork]  //undefined

我知道可以使用 eval 来完成,但由于服务器设置的原因,这不是一个选项。

您可以使用 Lodash#get:

let someObject = {
  nonProblematicValue: "all good",
  arrayOfValues: ["can't touch this"]
}

let keyThatDoesNotWork = "arrayOfValues[0]"
console.log(_.get(someObject, keyThatDoesNotWork))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>