$scope.addUserJson = $scope.adduser;
console.log($scope.addUserJson);
输出
Object {"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"mik@gmail.com"}
$scope.usergroup = $scope.usergroupmodel;
console.log($scope.usergroup);
输出
[Object{"grpid":"1","username":"Vikram911","firstname":"Vikram","lastname":"Doe","email":"vik@gmail.com","gender":"Male",
"description":"BLAH BLAH","phone":"5858585"},{"grpid":"2","username":"Varun091","firstname":"Varun","lastname":"Doe",
"email":"varun@gmail.com","gender":"Male","description":"BLAH BLAH","phone":"898989"}]
合并两个对象
$scope.object = angular.toJson(angular.merge({}, $scope.usergroup, $scope.addUserJson));
console.log($scope.object);
输出
[{"grpid":"1","username":"Vikram911","firstname":"Vikram","lastname":"Doe","email":"vik@gmail.com","gender":"Male",
"description":"BLAH BLAH","phone":"5858585"},{"grpid":"2","username":"Varun091","firstname":"Varun","lastname":"Doe",
"email":"varun@gmail.com","gender":"Male","description":"BLAH BLAH","phone":"898989"}]
如何合并上面两个json响应,以便它应该形成如下所示的最终结果
{"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"mik@gmail.com","grpid":["1,2"]}
答案 0 :(得分:0)
您不能只将对象与数组合并,也不能只将一个字段合并到合并中。
您可以使用JS数组映射函数在一行中手动设置addUserJson对象的grpid:
$scope.addUserJson.grpid = $scope.usergroup.map(function(grp) { return grp.grpid; });
答案 1 :(得分:0)
通过将$scope.addUserJson
视为一个数组,我使它更有用......
如果它永远不会是一个数组,请通知我,以便我可以将其更改回单个json对象。
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.usergroup = [{"grpid":"1","username":"Vikram911","firstname":"Vikram","lastname":"Doe","email":"vik@gmail.com","gender":"Male",
"description":"BLAH BLAH","phone":"5858585"},{"grpid":"2","username":"Varun091","firstname":"Varun","lastname":"Doe",
"email":"varun@gmail.com","gender":"Male","description":"BLAH BLAH","phone":"898989"}]
$scope.addUserJson = [{"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"mik@gmail.com"}];
var result = [];
// console.log($scope.usergroup);
for(x in $scope.addUserJson){
// console.log($scope.addUserJson.username +"=="+ $scope.usergroup[x].username);
var temp=[];
for(y in $scope.usergroup){
if($scope.addUserJson[x].username.localeCompare($scope.usergroup[y].username)){
temp.push($scope.usergroup[y].grpid);
}
}
if(temp.length>0){
var result1 = $scope.addUserJson;
result1[0].grpid = temp;
result = result1[0];
temp=[];
}
}
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
</body>