i found code (https://stackoverflow.com/a/8817473/1778465), works nicely, when want value array such item 1 undefined, not sure can array items well. ideas?
this code:
var obj = { foo: { bar: {animals: [{name: "billy"},{name: "bob"},{name: "joe"}]}} }; var deep_value = function(obj, path){ (var i=0, path=path.split('.'), len=path.length; i<len; i++){ obj = obj[path[i]]; }; return obj; }; console.log(deep_value(obj, 'foo.bar.animals[1].name')); // should show "bob" the above gives me following error:
uncaught typeerror: cannot read property 'name' of undefined
you're there. code give want:
console.log(deep_value(obj, 'foo.bar.animals.1.name')); // should show "bob" edit: if still want use [1] syntax array, here alternative version (split path ., [ , ]:
var obj = { foo: { bar: {animals: [{name: "billy"},{name: "bob"},{name: "joe"}]}} }; var deep_value = function(obj, path){ (var i=0, path=path.split(/[\[\]\.]/), len=path.length; i<len; i++){ if (path[i]){ obj = obj[path[i]]; } }; return obj; }; console.log(deep_value(obj, 'foo.bar.animals[1].name')); // should show "bob"
Comments
Post a Comment