Backbone collection: Retrieve distinct values of a collection

孤人 提交于 2019-12-10 08:46:49

问题


I have backbone collection of models and would like to retrieve the distinct values of a certain property

If I have loaded data like the following into my collection:

[{brand:'audi',id:'1234'},
{brand:'audi',id:'3456'},
{brand:'bmw',id:'3456'}]

I would now want to get the distinct brands from the collection. The result should be:

['audi','bmw']

Looking at the Backbone and Underscore API I don't see anything obvious to achieve this. My current approach would be to use a library like jslinq

Am I missing anything obvious or does somebody have a better suggestion than jslinq?


回答1:


You can use pluck and then use uniq (example: http://jsfiddle.net/sCVyN/5/)

pluck

A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

uniq

Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.



来源:https://stackoverflow.com/questions/11599123/backbone-collection-retrieve-distinct-values-of-a-collection

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