1

How to append to a json object to existing json in angular js

I am having an object like this

$scope.object1 = {
  data1: 'abc',
  data2: 1
};


$scope.object2 = {    
  data3:"One",
  data4:["a","b","c"]
};

How to append $scope.object2 to $scope.object1

So the final data should be like this

$scope.object1 = {
  data1: 'abc',
  data2: 1,
  data3:"One",
  data4:["a","b","c"]
};

I am using this but its not working

angular.forEach($scope.object1, function(obj)
{              
    obj.data3 = $scope.object2.data3;

    obj.data4 = $scope.object2.data4;

});         

3 Answers 3

4

Use 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>

Sign up to request clarification or add additional context in comments.

3 Comments

how, sir please explain any dependency needed?
It is built-in function. There are no extra dependencies. Let me show it in a snippet.
hearts off.Thankyou Sir Working
2

Use JQuery extend method. https://api.jquery.com/jquery.extend/

$.extend( $scope.object1, $scope.object2 );

2 Comments

No additional dependencies (e.g. jQuery) are required. There is own function angular.extend for that
I didn't know about it. It is good to know that we have this function in angular. Thanks a lot.
0

Lodash probably has the easiest way of doing this:

var users = {
 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
};

var ages = {
  'data': [{ 'age': 36 }, { 'age': 40 }]
};


_.merge(users, ages);

result will be

{ 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.