Last active
August 29, 2015 14:07
-
-
Save neolitec/e9c1d2b62cb4234d2392 to your computer and use it in GitHub Desktop.
Property accessing in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var utils = (function() { | |
var utils = {}, | |
PROPERTY_REGEXP = /^(([a-z_][a-z0-9_]*\.?)+[a-z0-9_]+)$/i; | |
var checkProperty = function(propName) { | |
if(!PROPERTY_REGEXP.test(propName)) | |
throw new Error('Property ' + propName + ' misspelled'); | |
return propName; | |
}; | |
utils.getProperty = function(obj, propName) { | |
var props = checkProperty(propName).split('.'), | |
current = obj; | |
try { | |
for(var i in props) { | |
current = current[props[i]]; | |
} | |
} catch(e) { | |
throw new Error('Cannot read property ' + propName + ' of ' + JSON.stringify(obj, null, '\t')); | |
} | |
return current; | |
} | |
utils.setProperty = function(obj, propName, value) { | |
var props = checkProperty(propName).split('.'), | |
propToSet = props.pop(), | |
current = utils.getProperty(obj, props.join('.')); | |
current[propToSet] = value; | |
return obj; | |
} | |
return utils; | |
})(); | |
var a = {"id":null,"caracteristique":{"datePrevue":"2014-11-01T01:00:00.000Z","dateReelle":null,"montantDepense":0,"solde":"0 €","dateDebutPeriode":null,"dateFinPeriode":null,"commentaire":null},"attributaire":{"attributaire":{"attributaire":null,"critereIndividu":null,"moyenPaiement":null,"critereMoyenPaiement":null}},"evenementComptable":{"listeEvenementComptable":{"options":{"data":[],"schema":{"model":{"id":"id","fields":{"id":{"type":"number","name":"id"},"montant":{"type":"string","name":"montant"},"evenement":{"type":"string","name":"evenement"},"date":{"type":"date","name":"date"},"reference":{"type":"string","name":"reference"},"autreInformation":{"type":"string","name":"autreInformation"}}}},"serverSorting":false,"serverPaging":false,"serverFiltering":false,"serverGrouping":false,"serverAggregates":false,"batch":false,"pageSize":5},"_map":{},"_prefetch":{},"_data":[],"_pristineData":[],"_ranges":[{"start":0,"end":0,"data":[]}],"_view":[],"_pristineTotal":0,"_destroyed":[],"_pageSize":5,"_page":1,"_group":[],"_total":0,"_events":{"change":[null,null,null,null,null,null,null,null],"progress":[null],"error":[null]},"transport":{"data":[]},"reader":{},"table":null,"_skip":0,"_take":5,"_requestInProgress":false,"_aggregateResult":{}}}}; | |
a.aze; | |
console.log(utils.getProperty(a, 'caracteristique')); | |
console.log(utils.getProperty(a, 'caracteristique.montantDepense')); | |
console.log(utils.setProperty(a, 'caracteristique.montantDepense', 10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment