0

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?

4
  • Define "won't work". What is the code, what is the input, what is the expected output, what is the actual output (or error)? Commented Sep 14, 2017 at 19:17
  • the expected outcome is for it to log {"domain":"localhost","zip":33333, "id":"210","name":"sam"}, instead it logs [object object] Commented Sep 14, 2017 at 19:21
  • You answered 1 of the 4 questions. Answer the 3 others. You didn't post any code that logs anything. Commented Sep 14, 2017 at 19:23
  • jsonOne and jsonTwo are not objects. They are strings. angular.toJson() takes an object and transforms it to a JSON string. Commented Sep 14, 2017 at 19:24

1 Answer 1

2

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" }
Sign up to request clarification or add additional context in comments.

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.