javascript Underscore.js - 获取唯一的属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21557431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Underscore.js - get unique property values
提问by Iladarsda
I only recently discovered the power of underscore.js, still new to the methods I kindly ask for a suggestion:
我最近才发现 underscore.js 的强大功能,对我恳请建议的方法仍然很陌生:
How do I get from this:
我如何从中获得:
[
[{
"name": "Type 2",
"id": 14
}],
[{
"name": "Type 1",
"id": 13
}, {
"name": "Type 3",
"id": 15
}],
[{
"name": "Type 2",
"id": 14
}],
[{
"name": "Type 1",
"id": 13
}]
]
to this:
对此:
["Type 1","Type 2","Type 3"]
i.e. no duplicated and "name" property only.
即没有重复的“名称”属性。
Any suggestions much appreciated.
任何建议非常感谢。
回答by Jakub Roztocil
_(data).chain().flatten().pluck('name').unique().value()
(Convert the nested lists to a flat one, pick name
from each of the objects in the list, and make it unique.)
(将嵌套列表转换为平面列表,name
从列表中的每个对象中挑选,并使其唯一。)
回答by McGarnagle
回答by Alex_Crack
var arr = _.uniq(_.map(_.flatten(array), function(e) {
return e.name;
}));
回答by Praveen Gubbala
_.uniq(_.pluck(x,'name'));
the above code is sufficient for extracting different "name" attribute
上面的代码足以提取不同的“名称”属性
回答by L?c ?oàn ?ình
Simple way:
简单的方法:
1. use _.map to get all the names
1.使用_.map获取所有名称
var names = _.map(items, function(item) { return item.name});
2. Get the _.uniq from that names
2. 从那个名字中获取 _.uniq
var uniqueNames = _.uniq(names);