📜 ⬆️ ⬇️

SteelToe - object, don't shoot me in the leg!

SteelToe is a small javascript snippet designed to solve the problem of access to undefined object properties. This is especially important when referring to nested properties. It also realized the possibility of autovivification, which in order simplifies the creation of the desired properties. In general - quite useful sugar in OOP.




Getting values


First way

var object = { info: { name: { first: 'Jonathan', last: 'Clem' } } } steelToe(object)('info')('name')('last')(); // 'Clem' steelToe(object)('info')('features')('hairColor')(); // undefined 

Second way

 var object = { info: { name: { first: 'Jonathan', last: 'Clem' } } } steelToe(object).walk('info.name.last'); // 'Clem' steelToe(object).walk('info.features.hairColor'); // undefined 


Determination of values


 var jonathan = { info: { name: { first: 'Jonathan', last: 'Clem' } } }, steelToe(jonathan).set('info.name.middle', 'Tyler'); steelToe(jonathan).set('info.favorites.movie', 'Harold & Maude'); jonathan.info.name.middle; // Tyler jonathan.info.favorites.movie; // Harold & Maude 


What's going on here


Imagine - you have a complex Javascript object, with a lot of nesting of properties, which you, say, got from JSON. And, for example, you need to do something like this:
')
 var fatherFirstNames = []; for (var i = 0; i < families.length; i ++) { var first = families[i].father.info.name.first; if (first) { fatherFirstNames.push(first); } } // TypeError: 'undefined' is not an object (evaluating 'family.father.info.name.first') 


- Bliiin !, you say - a dull shot in the leg! At you TypeError error can easily fall TypeError , since nothing guarantees that the father property is defined, or it has the properties you require. Usually, to prevent errors of this kind, we write wretchedness, like this

 var farherFirstNames = []; for (var i = 0; i < families.length; i++) { var father = families[i].father; if (father && father.info && father.info.name && father.info.name.first) { fatherFirstNames.push(father.info.name.first); } } 


Bueeee ... See how SteelToe elegantly solves this problem!

 var fatherFirstNames = []; for (var i = 0; i < families.length; i++) { var name = steelToe(families[i]).walk('father.info.name.first'); if (name) { fatherFirstNames.push(name); } } fatherFirstNames; // ["Hank", "Dale", "Bill"] 


No more TypeError s! Happiness!

The library is presented on the website , and in github .

Source: https://habr.com/ru/post/159269/


All Articles