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.
任何建议非常感谢。
5 个解决方案
#1
26
_(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.)
(将嵌套列表转换为平面列表,从列表中的每个对象中选择名称,并使其唯一。)
#2
#3
2
var arr = _.uniq(_.map(_.flatten(array), function(e) {
return e.name;
}));
#4
1
_.uniq(_.pluck(x,'name'));
the above code is sufficient for extracting different "name" attribute
上面的代码足以提取不同的“名称”属性
#5
0
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);
#1
26
_(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.)
(将嵌套列表转换为平面列表,从列表中的每个对象中选择名称,并使其唯一。)
#2
10
- Use
flatten
first, to convert the nested array to a flat array. - 首先使用展平,将嵌套数组转换为平面数组。
- Then
pluck
to get the "name" values as an array - 然后采取将“名称”值作为数组
- Finally
uniq
- 最后是uniq
_.uniq(_.pluck(_.flatten(items), "name"))
小提琴
#3
2
var arr = _.uniq(_.map(_.flatten(array), function(e) {
return e.name;
}));
#4
1
_.uniq(_.pluck(x,'name'));
the above code is sufficient for extracting different "name" attribute
上面的代码足以提取不同的“名称”属性
#5
0
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);