对象内部引用声明

时间:2012-12-03 15:17:26

标签: javascript

我正在注意使用字典中的值作为字典内部引用的快捷方式。代码显示了我的意思:

var dict = {
    'entrance':{
        'rate1': 5,
        'rate2':10,
        'rate3':20,
    },

    'movies':{
        'theDarkKnight':{
            '00:00':<entrance.rate1>,
            '18:00':<entrance.rate2>,
            '21:00':<entrance.rate3>
        },
        ...
    };

有一种偷偷摸摸的方法吗?

2 个答案:

答案 0 :(得分:9)

没有。你能做的最好的是:

var dict = {
    'entrance' : {
        'rate1' : 5,
        'rate2' : 10,
        'rate3' : 20,
    }
};
dict.movies = {
    'theDarkKnight' : {
        '00:00' : dict.entrance.rate1,
        '18:00' : dict.entrance.rate2,
        '21:00' : dict.entrance.rate3
    },
    ...
};

答案 1 :(得分:3)

您可以使用mustache并将您的json定义为“小胡子模板”,然后运行小胡子来渲染模板。考虑到如果您有嵌套依赖项,则需要运行(n)次。在这种情况下,您有3个依赖项ABC --> AB --> A

var mustache = require('mustache');

var obj = {
  A : 'A',
  AB : '{{A}}' + 'B',
  ABC : '{{AB}}' + 'C'
}

function render(stringTemplate){
  while(thereAreStillMustacheTags(stringTemplate)){
    stringTemplate = mustache.render(stringTemplate, JSON.parse(stringTemplate));
  }
  return stringTemplate;
}

function thereAreStillMustacheTags(stringTemplate){
  if(stringTemplate.indexOf('{{')!=-1)
    return true;
  return false;
}

console.log(render(JSON.stringify(obj)));

输出是:

{"A":"A","AB":"AB","ABC":"ABC"}
相关问题