我有一个包含两个项目数组的对象。这些项的结构相同,每个项都有一个“tech”属性,它是一个字符串数组。我想打印一个显示在所有对象中的所有可能的唯一字符串的数组。我在下面包含的解决方案有效,但我想知道是否有更简洁的方法来完成lodash的这项任务?
var data = {
"sitesA" : [
{
"name": "Website Alpha",
"tech": ["SASS", "Foundation", "jQuery"]
},
{
"name":"Website Beta",
"tech":["SASS","AngularJS"]
},
{
"name":"Website Charlie",
"tech":["CSS","WordPress"]
}
],
"sitesB" : [
{
"name":"OtherSite",
"tech":["CSS","jQuery"]
},
{
"name":"Bears",
"tech":["SASS","AngularJS"]
},
{
"name":"Taco Time",
"tech":["CSS", "ASP", "SQL"]
}
]
}
var tech = [];
_.each(data,function(collection){
_.each(collection,function(item){
_.each(item.tech, function(value){
tech.push(value);
});
});
});
console.log( _.uniq(tech) );
// ^ returns desired result of: ["SASS", "Foundation", "jQuery", "AngularJS", "CSS", "WordPress", "ASP", "SQL"]
答案 0 :(得分:2)
这个怎么样?
var tech = _.uniq(_.reduce(data, function (memo, collection) {
return memo.concat(_.flatten(_.map(collection, _.partial(_.get, _, 'tech'))));
}, []));
解释如下:
flatten
,你就会得到一个矩阵(我们不想要的东西,所以我们“扁平化”阵列) _.uniq
答案 1 :(得分:2)
var data = { "sitesA": [{ "name": "Website Alpha", "tech": ["SASS", "Foundation", "jQuery"] }, { "name": "Website Beta", "tech": ["SASS", "AngularJS"] }, { "name": "Website Charlie", "tech": ["CSS", "WordPress"] }], "sitesB": [{ "name": "OtherSite", "tech": ["CSS", "jQuery"] }, { "name": "Bears", "tech": ["SASS", "AngularJS"] }, { "name": "Taco Time", "tech": ["CSS", "ASP", "SQL"] }] },
tech = [];
_.each(data , function(collection){
tech.push(_.map(collection,'tech'));
});
console.log(_.uniq(_.flattenDeep(tech)));
答案 2 :(得分:1)
使用ES6,您可以使用Set
var data = { "sitesA": [{ "name": "Website Alpha", "tech": ["SASS", "Foundation", "jQuery"] }, { "name": "Website Beta", "tech": ["SASS", "AngularJS"] }, { "name": "Website Charlie", "tech": ["CSS", "WordPress"] }], "sitesB": [{ "name": "OtherSite", "tech": ["CSS", "jQuery"] }, { "name": "Bears", "tech": ["SASS", "AngularJS"] }, { "name": "Taco Time", "tech": ["CSS", "ASP", "SQL"] }] },
techSet = new Set;
Object.keys(data).forEach(k =>
data[k].forEach(o =>
o.tech.forEach((new Set).add.bind(techSet))));
console.log([...techSet]);