Read nested object property ( t('a.b.c') ) via string in JS
Imagine this object ('hash')
accessing =
an:
deeply:
nested:
attribute:
yeah: 'yeah yeah'
console.log accessing.an.deeply.nested.attribute.yeah
#output: yeah yeah
How to access this with a dynamic string? Reduce (from underscore.js or even the native one in Javascript 1.8 will come to rescue!
#use reduce to follow the key chain
window.t = (key, obj)->
_(key.split('.')).reduce( ((obj, key)-> obj[key]), obj)
#pass the chained key to access and the object
console.log t('an.deeply.nested.attribute.yeah', accessing)
#output: yeah yeah
I use this to access my translations in Rails in JS. Pay attention to error handling (e.g. key not found)
Written by George
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Attributes
Authors
Related Tags
#attributes
#keys
#hash
#helper
#array
#i18n
#method
#rails
#chain
#nested
#deep
#chained
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#