shroomingnewman
shroomingnewman

Reputation: 21

can't copy object properties to another in javascript

this should be simple enough, but i'm having trouble copying the properties of an object to another.

var tableFormatting = {
    table: {
        style: {
            width: "100px",
            height: "100px"
        },
        border: "1px"
    }
    //similar code for tbody, tr, td  
};
var table = document.createElement('table');
for (var p in tableFormatting.table)
table[p] = tableFormatting.table[p];
alert(table.style.width); //shows nothing. can't access it  
alert(typeof(table.style.width)); //shows string, so i know it was copied or has a reference
alert(table.border); //shows 1px. this one is copied and accessible 

why aren't the style properties displaying?

Upvotes: 2

Views: 188

Answers (1)

Esailija
Esailija

Reputation: 140210

You need to deep copy them

function copyValues( dst, src ) {
    for( var key in src ) {
        var value = src[key];
        if( typeof value == "object" ) {
            copyValues( dst[key], value );
        }
        else {
            dst[key] = value;
        }
    }
}

copyValues( table, tableFormatting.table );

see http://jsfiddle.net/RpJKH/

Otherwise, what's happening is the manual equivalent of:

 table.style = obj.style

And of course that does nothing, because .style is read-only.

Upvotes: 3

Related Questions