Last Updated: February 25, 2016
·
1.909K
· georgiee

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)