如何在angularjs中将两个数组合并为一个数组?

时间:2015-10-12 04:51:41

标签: javascript angularjs underscore.js

这是我的代码

$scope.studentDetails=[];

$scope.studentDetails=[0][id:101,name:one]
                      [1][id:102,name:two]
                      [2][id:103,name:three] 

$scope.studentMarks=[];

$scope.studentMarks=[0][id:101,marks:78]
                    [1][id:102,marks:89]

我有两个数组,第一个数组包含2个属性,如id和name,第二个数组包含两个属性,如id和标记,我想将这两个数组合并为一个数组。我希望得到像

这样的输出
$scope.studentDetails=[0][id:101,name:one,marks:78]
                      [1][id:102,name:two,marks:89]
                      [2][id:103,name:three,marks:null]

4 个答案:

答案 0 :(得分:2)

如果您的JavaScript首先有效,Lodash zip()应该这样做。

$scope.studentDetails = _.zip($scope.studentDetails, $scope.studentMarks);

答案 1 :(得分:1)

我得到了答案

var newArray = [];
_.each($scope.studentDetails,function(obj))
{
 var data=_.findWhere($scope.studentMarks,{"id":obj.id});
 if(!_.isUndefined(data))
 {
   newArray.push({id:obj.id,name:obj.name,marks:data.marks});
 }
else
 {
newArray.push({id:obj.id,name:obj.name,marks:"null"});
 }
}

答案 2 :(得分:0)

嘿,你可以使用像

这样的推送
$scope.studentDetails.push({'id':'101','name':'one','marks':'78'});
$scope.studentDetails.push({'id':'102','name':'two','marks':'78'});
$scope.studentDetails.push({'id':'103','name':'three','marks':'78'});

使用循环你可以像下面那样追加

for(i = 0; i < studentResult.length; i++){
    $scope.studentDetails.push(studentResult[i]);
}

答案 3 :(得分:0)

对于对象数组_.zip,将两个数组合并为单个数组,其中每个数组元素也是一个数组。

您可以使用 .map .extend创建合并对象数组{/ 3}}

var studentDetails = [{ id: 101, name: 'one' }, { id: 102, name: 'two' }, { id: 103, name: 'three' }];
var studentMarks = [{ id: 101, marks: 78 }, { id: 102, marks: 89 }];

var mergedArray = _.zip(studentDetails, studentMarks); //where each element also an array like [ [{ id: 101, name: 'one' }, { id: 101, marks: 78 }] ]

var studentDetails = _.map(mergedArray, function (item) { return _.extend(item[0], item[1]); }); //[{ id: 101, marks: 78, name: 'one' }, ..]