Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading