0

I have a problem regarding putting objects on array. I'm doing this for recording the history of the activity so I store every object on an array by pushing it inside. but when I push it the previous object data is updated with the current. I don't know where the problem is? I really need help in this. Thank you.

I've tried to clone the object by this:

function deepCopy(obj) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
        var out = [], i = 0, len = obj.length;
        for ( ; i < len; i++ ) {
            out[i] = arguments.callee(obj[i]);
        }
        return out;
    }
    if (typeof obj === 'object') {
        var out = {}, i;
        for ( i in obj ) {
            out[i] = arguments.callee(obj[i]);
        }
        return out;
    }
    return obj;
}

but still no luck in here. :(

2
  • 7
    Code is missing Commented May 7, 2013 at 10:25
  • 1
    Please show your code. Commented May 7, 2013 at 10:25

1 Answer 1

2

The problem is most likely that you are pushing the same object over and over. Example:

var obj = {};
var arr = [];
for (var i = 0; i < 10; i++) {
  obj.index = i;
  arr.push(obj);
}

The result is an array with ten references to the same object.

You have to create a new object instance each time. Example:

var arr = [];
for (var i = 0; i < 10; i++) {
  var obj = {};
  obj.index = i;
  arr.push(obj);
}

The result is an array with ten references to ten separate objects.

Sign up to request clarification or add additional context in comments.

5 Comments

tnx for the quick response @guffa. I think you have pointed out the problem. But is it possible to copy the current object and just set it to a new object?
@rjx44: You would do that by creating a new empty object, and copy all properties from the original object. Usually it's easier to just create another instance of the original object.
I've pasted the code for copying but still it changes the previous data.
If you're using jQuery, you can simply go, var copy = $.extend({}, original);
@rjx44: Note that cloning like that is shallow. If your object contains any objects or arrays, you have to clone those also to make a deep cloning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.