Here is what's wrong with your code:
Do not use variable names like
_o. Get an editor with good auto-completion.typeof _o != 'object'does not do what you think it does:typeof([1,2]) // "object". In general, doing those kinds of checks is a code smell.if (!isNaN(parseInt(loc))) loc = parseInt(loc);. Confusing and not needed.
JavaScript:['a', 'b']["1"] // 'b'. Same goes for the otherisNaNin. Do not do that check.nullis a value, but what you want to return is the lack of value. It isundefinedin JavaScript, and it is what will be returned if there is no value.Consider using
splitinstead ofindexOfandsubstring. It is much faster and makes the code more readable.
So, here is a neat version for you:
function chained(obj, chain, value){
var assigning = (value !== undefined);
// split chain on array and property accessors
chain = chain.split(/[.\[\]]+/);
// remove trailing ']' from split
if (!chain[chain.length - 1]) chain.pop();
// traverse 1 level less when assigning; remove trailing ']' from split assigning
var n = chain.length - assigning - !chain[n - 1];assigning;
for (var i = 0, data = obj; i < n; i++) {
data = data[chain[i]];
// if (data === undefined) return; // uncomment to handle bad chain keys
}
if (assigning) {
data[chain[n]] = value;
return obj;
} else {
return data;
}
}
Blogged: http://glebm.blogspot.com/2011/01/javascript-chained-nested-assignment.html
Please come up with further improvements :)