Here I am in a situation where I have to work only with strings, and because of this I also have to retrieve the value of an object from strings, in short:
to retrieve the value from an object we write:
someObject.property1.name // for say
but in my case i want to retrieve value from an object using string, i.e
'someObject.property1.name' // for say
since I was not so confident that I could do this, so I preferred tho search on internet and the most suitable solution which I got was
#1
Object.byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
while (a.length) {
var n = a.shift();
if (n in o) {
o = o[n];
} else {
return;
}
}
return o;
}
from here
#2
var deep_value = function(obj, path){
for (var i=0, path=path.split('.'), len=path.length; i<len; i++){
obj = obj[path[i]];
};
return obj;
};
from here
but as I said they are the most suitable example because they all are taking one extra parameter i.e. obj
, O
and so on... which is creating trouble for me, so I tried to improve the above code in search 2 because it is compact, and that results in failure. That code is:
var obj = {
foo: { bar: 'baz' }
};
var deep_value = function(path){
var obj = path.split('.');
obj = obj[0];
for (var i=0, path=path.split('.'), len=path.length; i<len; i++){
obj = obj[path[i+1]];
};
return obj;
};
alert(deep_value('obj.foo.bar'));
(I edited in his code for just an experiment). the above code does not need obj which is a perfect code - if it worked - and don't see any mistake, then why this code is not working, what is the correct code?
thanks in advance