mustache 获取json数据内数组对象指定元素的方法

由于最近项目再用mustache,因此发现了这个问题,mustache无法获取json数据内数组键值的指定索引的元素

遂上网查资料总结一下两种方法

1,数据为数组对像

var obj = [{name: 'foo'}, {name: 'bar'}];

var tmp = '{{#1}}{{name}}{{/1}}';

console.log(Mustache.render(tmp, obj));

//bar

  这种方法个人觉得有一定局限性

            -----参照:http://stackoverflow.com/questions/6516297/can-mustache-iterate-a-top-level-array

2,数据为对象内数组对象

var obj1 = {
    'authors':[{name: 'foo'}, {name: 'bar'}]
};

for(var i = 0, len = obj1.authors.length; i < len; i++){     
    obj1.authors[i].index = i;
};

var tmp1 = '{{authors.0.name}}';

console.log(Mustache.render(tmp1, obj1));

//foo

这个代码个人觉得是比较完善的一种,不过不太适用大数据

            ------参照:http://www.kuqin.com/shuoit/20131012/335580.html

原文地址:https://www.cnblogs.com/hpuzy0127/p/5689257.html