'Is there an easy way to use nested object > array key in string form? [duplicate]
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 1:[1]
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/[email protected]/lodash.min.js"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jabaa |
