Phil Cross
Phil Cross

Reputation: 9302

jQuery Merging 2 objects with dynamic properties

I have 2 javascript objects. I need to merge them together, however one of them contains dynamic form field values, saved to variables.

I have some example code here: http://jsfiddle.net/ZAa7L/

I got this code from another question on stackoverflow, and their example worked fine.

My problem is, whenever I run it, I get the javascript error: Uncaught SyntaxError: Unexpected token s

This is seriously infuriating me, as if I replace the variable name in the data1 object with a literal string, it works fine.

Any ideas how to get the startDay property to use a variable?

Many thanks

Phil

Upvotes: 0

Views: 31

Answers (1)

VVV
VVV

Reputation: 7593

You can simply concatenate the string like this

var startDayVar = 1;

var data1 = '{ "startDay" : ' + startDayVar + '}';
var data2 = '{ "applicationId": "events.save"}';

var json1 = JSON.parse(data1);
var json2 = JSON.parse(data2);

var obj = $.extend({},json1,json2);
console.log(obj);

FIDDLE

Upvotes: 1

Related Questions