Lodash:提取属性,拆分数组,获取唯一值

时间:2018-06-27 04:51:52

标签: javascript arrays split lodash

在我的JS项目中,我正在使用Lodash库提取属性,拆分数组并获取唯一值。

  var taskobj = [
      {'taskno':'a', 'team':'1,2'},
      {'taskno':'b', 'team':'3,4'},
      {'taskno':'c', 'team':'2,4'},
    ];

 //Looping through the object to convert string to array
  _.forEach(taskobj, function(value, key) {
    taskobj[key].team = _.split(taskobj[key].team,',');
  });

// using _.map to extract team and return array
// using _.flatten to flatten array
// using _.uniq to get unique values from flattned array.

return _.uniq(_.flatten(_.map(taskobj,'team')));
// logs - [1,2,3,4]

这是实现这一目标的最有效方法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用reduce并以new Set()开头,并每次添加team的值(然后使用spread operator将其转换回数组)

var taskobj = [
  {'taskno':'a', 'team':'1,2'},
  {'taskno':'b', 'team':'3,4'},
  {'taskno':'c', 'team':'2,4'},
];

var result = [...taskobj.reduce((acc, {team}) => {
  team.split(',').forEach(e => acc.add(e))
  return acc
}, new Set())]

console.log(result)

答案 1 :(得分:1)

使用更简单的版本

尝试

var teams = [];
var taskobj = [
      {'taskno':'a', 'team':'1,2'},
      {'taskno':'b', 'team':'3,4'},
      {'taskno':'c', 'team':'2,4'},
    ];

taskobj.map(obj => {
  var teamSplit = obj.team.split(',');
  teams = [...teams, ...teamSplit];
})

var uniqTeams = _.uniq(teams);
console.log('teams', teams);
console.log('uniqTeams', uniqTeams)

JsBin链接 http://jsbin.com/bedawatira/edit?js,console

答案 2 :(得分:1)

这可以通过使用带有迭代器的lodash#flatMap来实现,该迭代器将team字符串拆分成一个数组,然后通过上述函数对其进行展平,然后使用lodash#uniq获得最终值结果。

var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));

var taskobj = [
    {'taskno':'a', 'team':'1,2'},
    {'taskno':'b', 'team':'3,4'},
    {'taskno':'c', 'team':'2,4'},
];

var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));

console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>