I'm trying to create a generic i18n solution for a HTML app I'm working in. I'm looking for alternatives to use eval() to call deeply nested Javascript objects:
Suppose the following HTML example:
<div id="page1">
<h1 data-i18n="html.pageOne.pageTitle"></h1>
</div>
and it's companion Javascript (using jQuery):
var i18n;
i18n = {
html: {
pageOne: {
pageTitle: 'Lorem Ipsum!'
}
}
};
$(document).ready(function () {
$('[data-18n]').each(function () {
var q;
q = eval('i18n.' + $(this).attr('data-i18n'));
if (q) {
$(this).text(q);
}
});
});
Any advices on how to access the "pageTitle" property inside the i18n object without using eval()? I need to keep the object's structure, so changing its layout to a "flat" solution is not feasible.
Thanks!!!
You can split the string on the periods and traverse the object:
Demo: http://jsfiddle.net/GsVsr/
You can use bracket syntax, as others have hinted at. But, you'll need to split and iterate at
.
:Then:
The dot syntax (
object.field
) is really just syntactic sugar forobject['field']
. If you find yourself writingeval('object.'+field)
, you should simply writeobject['field']
instead. In your example above, you probably want:i18n[$(this).attr('data-i18n')]
.Since you're encoding your attribute in a way that has dots in it, try splitting it by the dots, and iterating over the fields. For example (this can probably be improved):
You'll want to do additional checking to make sure all of the fields were handled, nulls weren't encountered, etc.