如何使用下划线将行项目合并到组?

时间:2016-05-02 19:00:03

标签: javascript angularjs underscore.js

我有一个对象列表:

var list = [
   {owner_email: "maxim", value: "v1"},
   {owner_email: "maxim", value: "v2"},
   {owner_email: "vlad", value: "v3"},
   {owner_email: "maxim", value: "v4"},
   {owner_email: "bob", value: "v5"},
   {owner_email: "bob", value: "v6"},
   {owner_email: "bob", value: "v7"},
   {owner_email: "vlad", value: "v8"},
   {owner_email: "maxim", value: "v9"},
   {owner_email: "maxim", value: "v10"},
   {owner_email: "bob", value: "v11"}
   ];

我想使用underscores将行项目合并到群组中。

所以输出应该如下:

output: [
{owner_email: "maxim", values: ["v1", "v2"]},
{owner_email: "vlad", values: ["v3"]},
{owner_email: "maxim", values: ["v4"]},
{owner_email: "bob", values: ["v5", "v6", "v7"]},
{owner_email: "vlad", values: ["v8"]},
{owner_email: "maxim", values: ["v9", "v10"]},
{owner_email: "bob", values: ["v11"]}
]

正如您所看到的,例如,在list前两项电子邮件中,请参阅maxim,因此我将第一行和第二行分组为:{owner_email: "maxim", values: ["v1", "v2"]},

如何让它发挥作用?

这是我到目前为止写的:

$scope.result = [];

     for(var i=0; i<list.length; i++){
       if(i === 0){
         $scope.result.push({
             owner_email: list[i].owner_email,
             values: [list[i].value]
         });
       }
       else{

       var item = list[i];
       var oldItem = _.findWhere($scope.result, {owner_email:item.owner_email});
       if(!oldItem ){
        $scope.result.push({
             owner_email: item.owner_email,
             values: [item.value]
         });
       }
       else{
       console.log(oldItem);

       angular.forEach($scope.result, function(_r){
           if(_r.owner_email === oldItem.owner_email){
              _r.values.push(item.value);
           }
           else{
           row = false;
           }
        });
       }
     }// for 

This is a demo I play with

1 个答案:

答案 0 :(得分:1)

这是一个只迭代列表并跟踪当前项目的解决方案:

var output = [];
var current = { owner_email: null };

_.each( list, function(item){
    if( item.owner_email != current.owner_email){
        current = { owner_email : item.owner_email, values: [item.value]};
        output.push(current);
    }
    else {
        current.values.push(item.value);
    }
});