Just a quick sketch of a possible way:
Your details :
var data = [ {foo: 1, bar: 2, foobar: [ 'a', 'b', 'c' ]}, {foo: 1, bar: 2, foobar: [ 'd', 'e', 'f' ]}, {foo: 1, bar: 2, foobar: [ 'g', 'h', 'i' ]} ]; var accessor = '1.foobar.2';
Using helper function :
function helper(data, accessor) { var keys = accessor.split('.'), result = data; while (keys.length > 0) { var key = keys.shift(); if (typeof result[key] !== 'undefined') { result = result[key]; } else { result = null; break; } } return result; }
Or make it accessible to all objects : (I personally don’t like it ...)
Object.prototype.access = function (accessor) { var keys = accessor.split('.'), result = this; while (keys.length > 0) { var key = keys.shift(); if (typeof result[key] !== 'undefined') { result = result[key]; } else { result = null; break; } } return result; };
Debug output :
console.log( helper(data, accessor), // will return 'f' data.access(accessor) // will return 'f' );
source share