Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i join two json objects together?

I have got a task to do user editing. I did this. But i cannot pass the value as json object. How can i join two values. My first object is

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        }
        else {
                
                o[this.name] = this.value || '';
        }
    });
    
    return o;
};

My second object is

var location = function() {
    var self = this;
    self.country = ko.observable();
    self.state = ko.observable();
};
 
var map = function() {

    var self = this;
    self.lines = ko.observableArray([new location()]);
    self.save = function() {
        var dataToSave = $.map(self.lines(), function(line) {
            return line.state() ? {
                state: line.state().state,
                country: line.country().country
            } : undefined
        });
        alert("Could now send this to server: " + JSON.stringify(dataToSave));
    };
};
 
ko.applyBindings(new map());

});

I want to concatenate this. I tried this but i got an error

$.ajax({
        url: '/users/<%[email protected]%>',
        dataType: 'json',
        //async: false,
        //contentType: 'application/json',
        type: 'PUT',
        data: {total_changes: JSON.stringify(dataToSave) + JSON.stringify($("#edit_user_1").serializeObject())},
        //data:JSON.stringify(dataToSave),
        //data:dataToSave,
        success: function(data) {
            alert("Successful");
          },
          failure: function() {
            alert("Unsuccessful");
          }
        });

When i run this it shows an error like this in terminal.

How can i solve this?

like image 520
Nithin Viswanathan Avatar asked Jun 15 '26 23:06

Nithin Viswanathan


1 Answers

If you have json1 and json2 objects you can do:

$.extend(json1, json2); 

So in json1 you will get both objects merged.

like image 103
spekdrum Avatar answered Jun 18 '26 14:06

spekdrum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!