It's very common to need to get a value from an object in javascript, and the trouble is when I'm trying to get a value or see if there is a value for some nested object key, I have to do things like this
// access deeply nested values...
obj['key1'] &&
obj['key1']['key2'] &&
obj['key1']['key2']['key3'] &&
obj['key1']['key2']['key3']['key4']
There are many solutions online for this but all I've found use some methods and concepts I don't understand as a beginner, like map/reduce methods or hasOwnProperty method or other methods.
Is it possible to do this with a simple for loop of the kind:
function getValueAt(searchPath) {
for (i = 0; i < searchPath.length; i++) {
/* implementation */
}
return
}
Arrays are javascript objects, and this helper function should support searching array objects and non-array objects.
The return result should be undefined if searchPath
doesn't exist, and should be the value if it does exist.
How the getValueAt
function would be called:
getValueAt(obj['key1']['key2']['key3']['key4'])
So the function should check if obj
exists, then check if each passed property is not undefined, one at a time, then finally get the value if it passes all those checks, otherwise return undefined