skip to Main Content

I’m creating an array of objects in Javascript. The object data is being generated on the fly in a for loop.

When you run this code you’ll see that the final array generated in the console log is all the same data for each index.

I’m new to Javascript, but I do have experience with arrays in C++, Python, VBA, etc.

I realize there are other types of loops for arrays like ForEach, and Mapping, but
this seems like it should be very straightforward, but I have no idea what I’m missing.

const test_data = {
  value: 0,
  value2: 0
};

let number = 10;

let test_array = [];
let temp = test_data;

for (let i = 0; i < number; i++) {

  //i realize using a temp object is a little redundant
  //being that i could just say test_array[i].value = ***
  //i get the same results either way.
  temp.value = 500 * (i + 1);
  temp.value2 = temp.value * 100;

  test_array.push(test_data);
  test_array[i] = temp;

  console.log(temp);
  console.log(test_array[i]);
  console.log(test_array);

}

console.log(test_array);

3

Answers


  1. Objects are passed by reference in JS, so in your code on each iteration you are modifying the same object and adding a link to it in your array.

    You will have to either create copies of the temp object whenever you add it to the array or, since you modify all properties, create a new object and set it before adding it.

    let number = 10;
    let test_array = [];
    
    for (let i = 0; i < number; i++) {
      const temp = {};
      temp.value = 500 * (i + 1);
      temp.value2 = temp.value * 100;
    
      test_array.push(temp);
    }
    
    console.log(test_array);

    Or if you wan to create copies from the original (because there are other data you want to keep)

    const test_data = {
      value: 0,
      value2: 0,
      common_data: 'some common value'
    };
    
    let number = 10;
    
    let test_array = [];
    
    for (let i = 0; i < number; i++) {
      // create shallow copy
      const temp = {...test_data};
      
      temp.value = 500 * (i + 1);
      temp.value2 = temp.value * 100;
    
      test_array.push(temp);
    }
    
    console.log(test_array);

    Finally, if you want to create copies and the test_data holds other objects in it, you might want to do a deep copy instead

    Login or Signup to reply.
  2. As @Stephen Quan mentioned in his comment you have multiple reference and reference to the same object.

    To solve this issue you can use the spread operator to create the new copy of the object.

      for (let i = 0; i < number; i++) {
        let temp = test_data;
    
        temp.value = 500 * (i + 1);
        temp.value2 = temp.value * 100;
        test_array[i] = {...temp};
      }
    
    Login or Signup to reply.
  3. Check if this is what you are looking for

    const test_data = {
        value: 0,
        value2: 0
    };
    
    const start = 1;
    const end = 10;
    const number = [...Array(end - start + 1).keys()].map(x => x + start);
    
    const test_array = number.map((_, index) => {
        let value = 500 * (index + 1);
        let value2 = value * 100;
        return {value, value2};
    });
    
    console.log(test_array);
    

    Output:

    [
        {
            "value": 500,
            "value2": 50000
        },
        {
            "value": 1000,
            "value2": 100000
        },
        {
            "value": 1500,
            "value2": 150000
        },
        {
            "value": 2000,
            "value2": 200000
        },
        {
            "value": 2500,
            "value2": 250000
        },
        {
            "value": 3000,
            "value2": 300000
        },
        {
            "value": 3500,
            "value2": 350000
        },
        {
            "value": 4000,
            "value2": 400000
        },
        {
            "value": 4500,
            "value2": 450000
        },
        {
            "value": 5000,
            "value2": 500000
        }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search