0

Say I have multiple arrays.

var array1= [];
var array2= [];
var array3= [];

And I have another array of objects, each with a health parameter. Say I push the first object in this array into array1, array2 and array3.

Now if I edit the health parameter of array1's object:

array1[0].health -= 50

it changes the health for each arrays object. How can I do it so it only does it for the array im calling into?

AlwaysNeedingHelp
  • 1,851
  • 3
  • 21
  • 29

3 Answers3

2

If you want a copy of the object in each array, and you don't want the modification of one to affect the others, then you will need to clone the object. The answers on this post will help you with this:

What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
Travesty3
  • 14,351
  • 6
  • 61
  • 98
1

Objects in javascript are assigned by reference so if you put the same object into two separate arrays, each array element points at exactly the same object.

If you want separate objects in each array, then you have to explicitly make a new object for the second array (copying properties from the first object if that's what you want).

In jQuery, you can use $.extend() to make a copy of an object. See this answer for two different ways to use it.

Or, in plain Javascript, here's a function that makes a shallow copy of a plain JS object.

function copyObj(src) {
    var copy = {};
    for (var prop in src) {
        if (src.hasOwnProperty(prop)) {
            copy[prop] = src[prop];
        }
    }
    return copy;
}
Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

var array1 = []

var array2 = []

array1.health = 50

array2.health = 10

console.log(array1.health)

50

it still remains 50. On the other hand if your question relates to changing array elements as such

var array1= [0,1]

array1[0].health = 50

array1[1].health = 10

console.log(array[0].health) will print out 10 because health is an property of the array object not the element.

Encinoman818
  • 231
  • 1
  • 2
  • 5
  • I think you may have misunderstood the question. It's more like `var obj = {health: 100}; var array1 = [obj]; var array2 = [obj]; array1[0].health -= 50; console.log(array2[0].health); /* outputs 50 */` - He's saying that he has appended the same object to multiple different arrays, and modifying the object in one array results in the object being modified in all arrays. – Travesty3 Oct 15 '14 at 01:19