Dustjs Display Unique Values Only?

假装没事ソ 提交于 2019-12-12 20:35:10

问题


Lets say i have the following JSON

{
   names: ["John", "Peter", "Ron", "John", "James", "John"]
}

I need DustJS to render the following names

John 
Peter
Ron
James

Notice that these are unique values in an array. Any ideas? Thank you so much!


回答1:


This can be done using a common algorithm to 'unique' an array:

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u.hasOwnProperty(this[i])) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

It's done by taking the values, attempting to add them as keys to an object (which will only work if they're different). If success, it adds that key to an array. If fail, it ignores the key. It then returns the array. I have a working dust.js demo here:

Working Demo




回答2:


I believe this will generate your "also acceptable" form:

{#options}] {.} {#variants} {.options[$idx]} {/variants} {/options}


来源:https://stackoverflow.com/questions/24566589/dustjs-display-unique-values-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!