Juan Arciniega
Juan Arciniega

Reputation: 21

how to concat two json objects in angularJs

I have the following in an angular controller:

var jsonOne = $cookies.get('test');
// console logs {"domain":"localhost","zip":33333}

var jsonTwo = angular.toJson($scope.formData);
// console logs {"id":"210","name":"sam"}

var final = $.extend(jsonOne, jsonTwo);
// console logs [object object]

My goal is to get:

var final
// console logs {"domain":"localhost","zip":33333, "id":"210","name":"sam"}

I'm asking under angular because when I try it in a static html document it works fine, but for some reason it wont work in angular. Any ideas?

Upvotes: 0

Views: 3675

Answers (1)

Nathan Beck
Nathan Beck

Reputation: 1191

The issue seems to be your use of angular.toJson, which from the docs serializes inputs as a JSON string. Using a string with angular.extend() won't work as you want.

Try to retrieve your elements without serializing them as a string - it seems like you might already have the objects and don't need to use .toJson.

Once you have your two objects, use angular.extend() to combine them.

var first = { "A": "B" };
var second = { "C": "D" };

var third = angular.extend(first, second);

console.log(third);
// in chrome it logs { A: "B", C: "D" }

Upvotes: 2

Related Questions