The utility function from this answer allows to easily access nested properties of objects and returns null (or undefined) if one of the parent properties does not exist.
original Code:
get = function(obj, key) { return key.split(".").reduce(function(o, x) { return (typeof o == "undefined" || o === null) ? o : o[x]; }, obj); } get(user, 'loc.lat') // 50 get(user, 'loc.foo.bar') // undefined
I really want to use this, but i need to be able to work with nested arrays as well.
Examples:
var childArray = [0,1,2]
var parentArray = [{myArray: childArray}]
var obj = {key: parentArray}
I want to extend the utility function like this:
get(obj, 'key[0].myArray[2]'); // 2
get(obj, 'key[0].foo[2]'); // null
get(obj, 'key[0].myArray[42]'); // null
And ideally it should also be able to evaluate this as well
var childArray = [0,1,2]
var parentArray = [childArray, childArray]
var obj = {key: parentArray}
get(obj, 'key[1][0]'); // 0
get(obj, 'foo[1][0]'); // null
Question:
Is it possible to access an array arr
with a given string-reference like "arr[0]"
(without regex to remove the brackets...)?
Do you know a more elegant solution that achieves the result presented in the examples above?