SteelToe
Don't shoot yourself in the foot while traversing JavaScript objects.
Get It
$ npm install steeltoe --save
Usage
SteelToe is a tiny JavaScript function that makes it safe to traipse about
objects without worrying about whether keys may or may not exist, and whether
it's safe to try and look inside of them. It also provides basic
autovivification of objects
through the set
function.
Getting Values
Method #1
var object = info: name: first: 'Jonathan' last: 'Clem' 'info''name''last'; // 'Clem''info''features''hairColor'; // undefined
Method #2
var object = info: name: first: 'Jonathan' last: 'Clem' ; // 'Clem'; // undefined
Setting Values
var jonathan = info: name: first: 'Jonathan' last: 'Clem' ;; jonathaninfonamemiddle; // Tylerjonathaninfofavoritesmovie; // Harold & Maude
Details
Let's say you've got some deeply nested data in JavaScript objects that you've just parsed from a JSON API response. For each result, you need to do something if there's some sort of data present:
var fatherFirstNames = ; for var i = 0; i < familieslength; i ++ var first = familiesifatherinfonamefirst; if first fatherFirstNames; // TypeError: 'undefined' is not an object (evaluating 'family.father.info.name.first')
Whoops! You shot yourself in the foot. You got a TypeError
because you had no
guarantee that the family had a father, or that the father had info present, or
that his name was returned! You fix it by writing this monstrosity:
var farherFirstNames = ; for var i = 0; i < familieslength; i++ var father = familiesifather; if father && fatherinfo && fatherinfoname && fatherinfonamefirst fatherFirstNames;
Or, you could use SteelToe and write this:
var fatherFirstNames = ; for var i = 0; i < familieslength; i++ var name = ; if name fatherFirstNames; fatherFirstNames; // ["Hank", "Dale", "Bill"]
The End
SteelToe was made when a coworker of mine said that he wished someone would write a JavaScript library that would allow him to traverse objects without shooting himself in the foot, and that the library was called SteelToe.