performance - Most efficient Javascript way to check if an object within an unknown object exists -
this question has answer here:
this come against quite in javascript. let's have object this:
var acquaintances = { types: { friends: { billy: 6, jascinta: 44, john: 91 others: ["matt", "phil", "jenny", "anna"] }, coworkers: { matt: 1 } } } in theoretical program, know sure acquaintances object; have no idea whether acquaintances.types has been set, or whether friends has been set within it.
how can efficiently check whether acquaintances.types.friends.others exists?
what is:
if(acquaintances.types){ if(aquaintances.types.friends){ if(acquaintances.types.friends.others){ // stuff "others" array here } } } aside being laborious, these nested if statements bit of nightmare manage (in practice objects have far more levels this!). if try if(acquaintances.types.friends.others){) straight off bat, , types hasn't been set yet, program crash.
what ways javascript have of doing in neat, manageable way?
an alternative approach is:
((acquaintances.types || {}).friends || {}).others which shorter other solutions, may or may not thrill you.
you can build little helper make same idea tiny bit more palatable:
function maybe(o) { return o || {}; } now can do
maybe(maybe(acquaintances.types).friends).others if don't mind writing property names strings, make little helper:
function maybe(obj) { return object.defineproperty( obj || {}, 'get', { value: function(prop) { return maybe(obj[prop]); } ); } now can write
maybe(acquaintances.types').get('friends').others in es6, can this, albeit clumsily, using destructuring assignment defaults:
var { types: { friends: { others } = {} } = {} } = acquaintances; if want use in expression context, instead of assigning variable, in theory use argument destructuring:
(({ types: { friends: { others } = {} } = {} }) => others)(acquaintances) after said , done, standard approach remains
acquaintances.types && acquaintances.types.friends && acquaintances.types.friends.others this why there active (?) discussion in es6 design groups coffeescript-like existential operator, not seem converging rapidly.
Comments
Post a Comment