有没有一种更简单的方法可以使用lodash从多个对象集合构造唯一值数组?

时间:2016-10-03 20:04:47

标签: javascript lodash

我有一个包含两个项目数组的对象。这些项的结构相同,每个项都有一个“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"]

3 个答案:

答案 0 :(得分:2)

这个怎么样?

var tech = _.uniq(_.reduce(data, function (memo, collection) {
    return memo.concat(_.flatten(_.map(collection, _.partial(_.get, _, 'tech'))));
}, []));

解释如下:

  1. 将阵列缩小为一个新的阵列,并将其变为“其内部组件的技术属性。
  2. 由于' tech'是一个数组,如果你没有申请flatten,你就会得到一个矩阵(我们不想要的东西,所以我们“扁平化”阵列)
  3. 使用_.uniq
  4. 删除重复的项目

答案 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]);