Search code examples
javascriptarraysnested-object

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


What I have is some kind of object, structure is unknown to me beforehand, and I also receive the key (in the string form) for some value that I need, that is contained inside that object. The problem arises when the value I need is nested inside an array.


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

I've tried

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

I know that it could be done using eval, but that is not an option because of the server setup.


Solution

  • You can use 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>