Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging Knockout JS Object with Javascript Object

I'm trying to asynchronously send some data as a single object. Half of the data is coming from my KnockoutJS viewModel. The other half is some data that I want to add on to that.

My thought was to convert them both to JSON objects, then use an array .concat to put them together. But this isn't working. Might you know why?

I've tried a few solutions. The first method builds an object from a JSON string, and then uses JSON.parse to put them as an object. The second tries to avoid strings altogether. Either way, after I get my objects I try concatenating them together, but without any luck.

With Strings

toAddString = '{"file": "thefile"}';
toAddObj = JSON.parse(toAddString);

koString = ko.toJSON(viewModel);
koObj = JSON.parse(koString,null,2);

finalObj = koObj.concat(toAddObj);

With Objects

toAddObj = [{"file": "thefile"}];

koObj = ko.toJS(viewModel);

finalObj = koObj.concat(toAddObj);

With Objects (2)

toAddObj = new Object();
toAddObj.file = "one";

koObj = ko.toJS(viewModel);

finalObj = koObj.concat(toAddObj);

Do you know what might be going wrong here?

All I want is a single object, be it an array or a JSON object, that contains the data from each of these sources.

like image 327
jamesplease Avatar asked Dec 19 '12 23:12

jamesplease


1 Answers

Try the following. I am guessing at the syntax, since I don't use Knockout myself, and I am using the ko.utils.extend() function to copy the properties of one object onto the other.

var toAddObj = { file: 'one' };

var koObj = ko.toJS(viewModel);

var finalObj = ko.utils.extend(toAddObj, koObj);

Note that without using var you are always creating global variables (typically a bad idea).

like image 158
GregL Avatar answered Nov 15 '22 03:11

GregL