0

I have a loop goes through an array of objects MyArrayOfObjects and then pushes the objects to a new array like this:

var NewArray = new Array();

for (i = 0; i < MyArrayOfObjects.length; i++) {

  TempObject = null;
  TempObject = new Object();

 // I have logic that copies certain properties but not others
 // but overall it looks like this:

  TempObject.prop1 = MyArrayOfObjects[i].prop1;
  TempObject.prop2 = MyArrayOfObjects[i].prop2;

  NewArray.push(TempObject);
}

As I loop through MyArrayOfObjects, I clear the TempObject and create a new one each time. Does NewArray contain the objects that I'm copying or just a reference to the objects copied and that then become deleted as the loop iterates?

Thanks.

4
  • What's the point of TempObject = null; if you have TempObject = new Object(); right after? Commented Dec 5, 2011 at 22:54
  • I want to be sure to clear the initial object before creating the new one. The null is not needed? Commented Dec 5, 2011 at 22:57
  • @frenchie Correct, it is not needed. Further, you should simply write var TempObject = {}; or even var TempObject = { prop1:MyArrayOfObject[i].prop1, prop2:MyArrayOfObjects[i].prop2 }; or even NewArray.push({ prop1:MyArrayOfObjects[i].prop1, prop2:MyArrayOfObjects[i].prop2 });; all three will result in 10 new objects being pushed into the array. Commented Dec 5, 2011 at 23:02
  • @Phrogz: there's a bunch of if statements to determine which properties to copy, that's why I'm doing it this way. Thanks for the null, I'll remove the line from my code. Commented Dec 5, 2011 at 23:05

3 Answers 3

3

It contains references to the objects themselves.

This code shows that concept in action (notice that changing the object after pushing it into the array changes the object in the array as well):

var ray = new Array();
var obj = { foo: 123 };

ray.push(obj);

obj.foo = 321;
alert(ray[0].foo);
Sign up to request clarification or add additional context in comments.

6 Comments

I have this in a loop: if my loops run 10 times, will I have 10 different objects in the array or 10 times the same object or something else?
Note that when you do var obj = { foo: 123 }, then obj is just a reference as well. If you then say obj = { foo: 456 }, the original object is unchanged. Since it would still be referenced in the loop, then looping through would allow for having many different objects, not many copies of the same object.
@frenchie I you use new Object or {} 10 times, you will have 10 distinct objects.
ok, so I'm fine with the way I do it or do I need to push with jQuery.extend?
@JonathanNewmuis: if obj points to foo:456, what happens to foo:123? Unchanged but inaccessible?
|
2
> var NewArray = new Array();

It is generally considered better to use an array literal to create an array. Variable names starting with a capital letter are, but convention, used for constructors. Using "new" at the start of a variable name can easily slip to become "new Array", and the name should reflect its purpose, so something like the following might be better:

var objectArray = [];

.

> for (i = 0; i < MyArrayOfObjects.length; i++) {

You should always declare variables, especially counters as undeclared variables are made properties of the global object (effectively global variables) when they are first assigned a value. Also, it is considered better to store the length of the array than get it in each iteration:

for (var i = 0, iLen = MyArrayOfObjects.length; i < iLen; i++) {

.

>   TempObject = null;
>   TempObject = new Object();

Again, declare variables. Assigning a value of null serves no useful purpose when you're going to assign some other value immediately afterward. Just do the second assignment (and use a literal):

  var TempObject = {};

.

>  // I have logic that copies certain properties but not others
>  // but overall it looks like this:
> 
>   TempObject.prop1 = MyArrayOfObjects[i].prop1;
>   TempObject.prop2 = MyArrayOfObjects[i].prop2;
> 
>   NewArray.push(TempObject);

At this point, TempObject and NewArray[NewArray.length - 1] both reference the same object.

> }

As I loop through MyArrayOfObjects, I clear the TempObject and create a new one each time.

There is no need to "clear" the object, just assign a new value to the variable. In javascript, all variables have a value that might be a primitive (e.g. string, number) or a reference to an object (e.g. Object, Array, Number, String)

Does NewArray contain the objects that I'm copying or just a reference to the objects copied and that then become deleted as the loop iterates?

It contains references to the new objects created on each iteration.

As variables hold references to objects, assigning a new value to the variable doesn't do anything to the object. When an object is no longer referenced by any variable or object property, it is made available for garbage collection and may be removed automatically at some later time when garbage collection runs.

1 Comment

ok, what happens to the "old" object when I do var TempObject = {}; every time the loop iterates? Does it remain but becomes inaccessible and creates some sort of memory leaks?
0

Using map or its jquery counterpart might be a more idiomatic way of doing this. For example:

var oldArray = [
    { prop1: 1, prop2: 10 },
    { prop1: 2, prop2: 20 },
    { prop1: 3, prop2: 30 }
]

var newArray = $.map(oldArray, function(oldObj) {
    return { newProp: oldObj.prop1 }
})

console.log(newArray)

1 Comment

I can't use that because I'm only copying parts of the object's properties based on some logic inside the loop.

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.