Javascript 如何在angularjs中合并两个对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29948680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How merge two objects array in angularjs?
提问by Muhammed Shihab
I want to append following object array with existing one in angulajs for implementing load more feature.
我想将以下对象数组附加到 angulajs 中的现有对象数组以实现加载更多功能。
ie,appending AJAX response with existing one each time.
即,每次附加 AJAX 响应与现有响应。
I have one variable, $scope.actionswhich contains following JSONdata,
我有一个变量,$scope.actions其中包含以下JSON数据,
{
"total": 13,
"per_page": 2,
"current_page": 1,
"last_page": 7,
"next_page_url": "http://invoice.local/activities/?page=2",
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I want to append following JSONresponse each time this variable.
我想在JSON每次这个变量时附加以下响应。
{
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I have tried with $scope.actions.data.concat(data.data);
我试过 $scope.actions.data.concat(data.data);
but it is not working and getting following error message
但它不起作用并收到以下错误消息
$scope.actions.data.concat is not a function
$scope.actions.data.concat is not a function
回答by Deblaton Jean-Philippe
You can use angular.extend(dest, src1, src2,...);
您可以使用 angular.extend(dest, src1, src2,...);
In your case it would be :
在您的情况下,它将是:
angular.extend($scope.actions.data, data);
See documentation here :
请参阅此处的文档:
https://docs.angularjs.org/api/ng/function/angular.extend
https://docs.angularjs.org/api/ng/function/angular.extend
Otherwise, if you only get new values from the server, you can do the following
否则,如果您只从服务器获取新值,则可以执行以下操作
for (var i=0; i<data.length; i++){
$scope.actions.data.push(data[i]);
}
回答by mbejda
This works for me :
这对我有用:
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
在您的情况下,它将是:
$scope.actions.data = $scope.actions.data.concat(data)
回答by shah
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
我有同样的问题,但我解决了这个问题
$scope.actions.data = [].concat($scope.actions.data , data)
回答by Nishchit Dhanani
Simple
简单的
var a=[{a:4}], b=[{b:5}]
angular.merge(a,b) // [{a:4, b:5}]
Tested on angular 1.4.1
在 angular 1.4.1 上测试

