Narasimha Maiya Narasimha Maiya - 5 months ago 12
AngularJS Question

Add an element to existing json in angularJs

I have 2 Json object as follows.

var j1={"fname":"XYZ","lname":"qwe"};


and

var j2 = {"id":"10"}


I want to merge
j1
and
j2


I tried with
var ob = angular.merge({},j1,j2);

but its showing angular.merge is not a function

I tried with
push
and
concat
. But these also gave same kind of error.

please help,
thank you.

Answer

If your version of Angular does not support angular.merge yet, you can use angular.extend instead.

angular.module('app', [])
.controller('TestController', ['$scope', function(){
  var j1 = {"fname":"XYZ","lname":"qwe"};
  var j2 = {"id": 10};
  var obj = angular.extend({}, j1, j2);
  
  console.log(obj);
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="TestController">
</div>

Note: angular.merge is only available from version 1.4 to the latest