user656925
user656925

Reputation:

Appending to an object literal

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 );

Upvotes: 0

Views: 878

Answers (3)

Julien Ch.
Julien Ch.

Reputation: 1261

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);
}

Upvotes: 2

David G
David G

Reputation: 96810

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

obj.dog = "woof";

This is also equivalent:

obj["dog"] = "woof";

Upvotes: 3

Joey
Joey

Reputation: 354536

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.

Upvotes: 2

Related Questions