Tflag Tflag - 3 years ago 260
Javascript Question

Why my object save only last data

I'm create two Object, struct_one and auxiliary struct_two for primary save a data.
After addet data with help ".push". Everything data from "struct_one[]" array, have a last the data.
Thank.



struct_one = { comments:[{comment:String}] };
struct_two = {comment:String};

function taskElementWork(){

this. createBlockSaveNew = function(){
struct_two.comment = 1 + "RED";
struct_one.comments.push(struct_two);
console.log(struct_one.comments[1].comment); // = 1RED
struct_two.comment = 2 + "RED";
struct_one.comments.push(struct_two);
console.log(struct_one.comments[2].comment); // = 2RED
struct_two.comment = 3 + "RED";
struct_one.comments.push(struct_two);
console.log(struct_one.comments[3].comment); // = 3RED

console.log( struct_one.comments[1].comment); // = 3RED -> Why!
}
}

test = new taskElementWork();
test.createBlockSaveNew();




Answer Source

You use the same object reference on pushing.

You could take a new object before assigning values and pushing, like

function taskElementWork() {
    var struct_two = { comment: '' };
    struct_two.comment = 1 + "RED";
    struct_one.comments.push(struct_two); 
    console.log(struct_one.comments[1].comment); // = 1RED

    struct_two = { comment: '' };
    struct_two.comment = 2 + "RED";
    struct_one.comments.push(struct_two); 
    console.log(struct_one.comments[2].comment); // = 2RED

    var struct_two = { comment: '' };
    struct_two.comment = 3 + "RED";
    struct_one.comments.push(struct_two); 
    console.log(struct_one.comments[3].comment); // = 3RED
}

A slighy better way, is to use a function for building the structure and take a parameter for the comment:

function taskElementWork() {
    function buildStructure(comment) {
        return { comment: comment };
    }

    struct_one.comments.push(buildStructure(1 + "RED")); 
    console.log(struct_one.comments[1].comment); // = 1RED

    struct_one.comments.push(buildStructure(2 + "RED")); 
    console.log(struct_one.comments[2].comment); // = 2RED

    struct_one.comments.push(buildStructure(2 + "RED")); 
    console.log(struct_one.comments[3].comment); // = 3RED
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download