如何将json对象附加到角度js中的现有json
我有一个像这样的对象
$scope.object1 = {
data1: 'abc',
data2: 1
};
$scope.object2 = {
data3:"One",
data4:["a","b","c"]
};
如何将$ scope.object2追加到$ scope.object1
所以最终的数据应该是这样的
$scope.object1 = {
data1: 'abc',
data2: 1,
data3:"One",
data4:["a","b","c"]
};
我正在使用它,但它无效
angular.forEach($scope.object1, function(obj)
{
obj.data3 = $scope.object2.data3;
obj.data4 = $scope.object2.data4;
});
答案 0 :(得分:4)
使用angular.extend($scope.object1, $scope.object2)
var app = angular.module('myApp', []);
app.controller("myCtrl", function ($scope) {
$scope.object1 = {
data1: 'abc',
data2: 1
};
$scope.object2 = {
data3:"One",
data4:["a","b","c"]
};
angular.extend($scope.object1, $scope.object2);
document.write(JSON.stringify($scope.object1));
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
</div>
</div>
答案 1 :(得分:2)
使用JQuery扩展方法。 https://api.jquery.com/jquery.extend/
$.extend( $scope.object1, $scope.object2 );
答案 2 :(得分:0)
Lodash可能有最简单的方法:
var users = {
'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
};
var ages = {
'data': [{ 'age': 36 }, { 'age': 40 }]
};
_.merge(users, ages);
结果将是
{ 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }