0

I pass an object literal to a function like this:

pre( {model:'MUserTry'} ); 

I then wish to augment it, but I end up writing over it like this.

    pre : function( o_p ) {
        o_p = {
            result: '0',
            page  : {}
        };

model is now gone as o_p is completely new

What is the best way to append object properties.

Do you have to explicitly define them now.

o_p.result = 0;
o_p.page = {};

or is there a function that will allow me to write out the object literal and combine them?

kind of like this

object1.push (object2 );
  • If you want to combine them http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically –  Jul 05 '12 at 21:31

3 Answers3

3

To add new object properties or methods, use the dot operator:

obj.dog = "woof";

This is also equivalent:

obj["dog"] = "woof";
David G
  • 94,763
  • 41
  • 167
  • 253
2

You can just add properties by assigning to them:

o_p.result = '0';

This won't create a new object and thus retain your model property.

Joey
  • 344,408
  • 85
  • 689
  • 683
2

In your code the local variable o_p is redefined by the assigning:

function( o_p ) {
    // assign a new value to local variable o_p
    // object passed as an argument is untouched
    o_p = {
        result: '0',
        page  : {}
    };
}

You could merge your objects like this :

function( o_p ) {
    var mergee = {
        result: '0',
        page  : {}
    };
    for (var attrname in mergee) { o_p[attrname] = mergee[attrname]; }    
}

Alternatively, if you can use JQuery, you can just use the extend method:

function( o_p ) {
    var mergee = {
        result: '0',
        page  : {}
    };
    $.extend(o_p, mergee);
}
Julien Ch.
  • 1,231
  • 9
  • 16
  • This question is also addressed more extensively [here](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically?lq=1) – Julien Ch. Jul 05 '12 at 21:41