0

I'm not looking native javascript only. I'm open to jQuery and underscore.js as well. I've googled a bit and I found questions/answers only explaining how to combine two objects and not more.

There is .extend from jquery which can do that. I'm looking for something that combines n objects with different properties into single object.

I'm actually doing a $('form').serializeArray() and then I get array of objects from the form. Is there a way I can get a single object from a form? Or how to combine more objects with different properties into single object?

London
  • 14,986
  • 35
  • 106
  • 147

1 Answers1

1

To convert a form to a json object use this. quote from answer above:

serializeArray already does exactly that, you just need to massage the data into your required format:

$.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;
};

To combine multiple objects use underscore extend:

_.extend({name: 'moe'}, {age: 50}, {test: "test"});

or jQuery extend:

$.extend({name: 'moe'}, {age: 50}, {test: "test"})
Community
  • 1
  • 1
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77