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.
toAddString = '{"file": "thefile"}';
toAddObj = JSON.parse(toAddString);
koString = ko.toJSON(viewModel);
koObj = JSON.parse(koString,null,2);
finalObj = koObj.concat(toAddObj);
toAddObj = [{"file": "thefile"}];
koObj = ko.toJS(viewModel);
finalObj = koObj.concat(toAddObj);
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With