问题
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