4 ms·
It is pretty common to use a function like this when digging into objects in general JS code: function get(p, o) { var parts = p.split('.'); for (
by oinksoft 14y ago
It is pretty common to use a function like this when digging into objects in general JS code:
function get(p, o) {
var parts = p.split('.');
for (var i = 0, l = parts.length; i < l; i++)
if (o.hasOwnProperty(parts[i]))
o = o[parts[i]];
else return undefined;
return o;
}
var o = { a: { b: { c: 1 } } };
console.log(get('a.b.c', o)); // 1
console.log(get('no.way', o)); // undefined
I'd be more likely to reuse something like that because it's already useful in the codebase than bringing on another library.
However, I am speaking out of ignorance, as it appears that the library you cite does a lot more than this simple thing: https://github.com/afeld/backbone-nested/blob/master/backbone-nested.js#L202 https://github.com/afeld/backbone-nested/blob/master/backbon...
In any case safe lookup methods are very useful!
- codewright 14y agoNot very composable or nice. Bespoke solutions are besides the point and the very thing I was decrying.
- deleted 14y ago[deleted]
- jQueryIsAwesome 14y agoYeah, is one of the things I don't like about JS. The typeof operator should be able to handle those cases. Or a new operator that returns a boolean would be nice. if(defined jQuery.unknown.propierties)