简体   繁体   English

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

[英]How to merge two arrays into one array in angularjs?

This is my code 这是我的代码

$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]

i have two arrays,first array contains 2 properties like id and name, second array contains two properties like id and marks,i want to concatinate these two arrays into one array.i want to get output like 我有两个数组,第一个数组包含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]

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

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

I got the answer 我得到了答案

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"});
 }
}

Hey you can use the push like 嘿,你可以使用像推

$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'});

using loop you can append like bellow 使用循环你可以像下面一样追加

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

For object array _.zip merged two array into single array where each array element also an array. 对于对象数组_.zip将两个数组合并为单个数组,其中每个数组元素也是一个数组。

You can use .map and 你可以使用.map .extend to create merged object array with _.zip like .extend_.zip创建合并对象数组

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' }, ..]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM