you could use the jquery extend method to do this
var originalData = {val1: value1, val2: value2};
var moreData = {val3: value3, val4: value4, val1: newValue1}; // i did newValue1 on purpose see below
$.extend(originalData, moreData); // this basically pushes the moreData into the originalData, it will also update any matching values to the new ones
so the final value will look like this
orignalData = {val1: newValue1, val2: value2, val3: value3, val4: value4};
hope this helps you can go here for more information on the jQuery extends api
Updated answer to include code to convert the string into a json Object
function convertBadJsonStringToGoodJsonObject(badString){
// expected format will not work with other format
// 'var4:value4,var5:value5,var6:value6'
// also assumes the the value4 and value5 VALUES are the "actual" string values of the key/value pair. if not then they will need to be put in the string.
var returnData = {};
// first split on ,
var keyValues = badString.split(",");
for(var i = 0; i < keyValues.length; i++){
// ok should be a list of items like this
// 'var4:value4
// now we need to split on the :
var keyValuePair = keyValues[i];
var pair = keyValuePair.split(":");
if (pair.length === 2){
var key = pair[0];
var value = pair[1];
// now convert this to a json object
var stringifiedJson = '{"' + key + '":"' + value + '"}';
// should look like this now
// '{"var4":"value4"}'
try{
var newProperJsonObject = JSON.parse(stringifiedJson);
$.extend(returnData, newProperJsonObject);
} catch (ex) {
// something went wrong with the parse, perhaps the original format wasnt right.
}
} // else not a valid pair
}
return returnData;
}
var badString = 'var4:value4,var5:value5,var6:value6';
var goodObject = convertBadJsonStringToGoodJsonObject(badString);
console.log(goodObject);
A few things to explain about the answer above. First, JSON format is a very specific format for data transport. While javascript uses a lazy version of it for its uses, the JSON.parse expects the string to be in a "real" json format. Which means the keys need to be surrounded by double-quotes. In javascript you can define an object as {val: value1} and life is good. But for for JSON.parse the string will need to be '{"val1":"value1"}'. If you pass it '{val1:value1}'. It will break and throw a javascript exception. Which is why I have it surrounded in a try catch.
I made the function purposely verbose but feel free to ask questions on it. Once your string object is properly converted the $.extend function will work as I explained earlier.