Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

javascript - Alternatives to eval() for multiple nested objects

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!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use bracket syntax, as others have hinted at. But, you'll need to split and iterate at .:

function lookup(obj, path) {
    var keys = path.split('.'),
        result = obj;

    for (var i = 0, l = keys.length; i < l; i++) {
        result = result[keys[i]];

        // exit early if `null` or `undefined`
        if (result == null)
            return result;
    }

    return result;
}

Then:

q = lookup(i18n, $(this).attr('data-i18n'));
if (q) {
  $(this).text(q);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...