gpt4 book ai didi

backbone.js - 如何从集合中查找不同值的数量

转载 作者:行者123 更新时间:2023-12-04 22:22:46 26 4
gpt4 key购买 nike

假设我有一个像这样的集合:

  {
"id": 1,
"name": "jonas",
},
{
"id": 2,
"name": "jonas",
},
{
"id":3,
"name": "smirk",
}

如何得到 :

不同名称的数量,例如在这种情况下,2

不同的名字,在这种情况下,乔纳斯和傻笑?

最佳答案

使用一些 Backbone 和 Underscore 魔法,结合 collection.pluck _.uniq :

pluck collection.pluck(attribute)
Pluck an attribute from each model in the collection. Equivalent to calling map, and returning a single attribute from the iterator.

uniq _.uniq(array, [isSorted], [iterator])
Produces a duplicate-free version of the array, using === to test object equality.
[...]


var c = new Backbone.Collection([
{id: 1, name: "jonas"},
{id: 2, name: "jonas"},
{id: 3, name: "smirk"}
]);

var names = _.uniq(c.pluck('name'));
console.log(names.length);
console.log(names);

和一个演示 http://jsfiddle.net/nikoshr/PSFXg/

关于backbone.js - 如何从集合中查找不同值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12009087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com