1

the following p5js code did not work , since the object in array are reference to the flower , how can i initialize the object with different values ?

var flowers;
var flower;

function setup()
{
    createCanvas(1000,500);
    base_x = width/2;
    base_y = height - 50;

    flowers = [];

    flower = {
        base_x: 0,
        base_y: height - 50,
        stem_h: 100,
        col: color(255,50,50)
    }

    for(var i = 0; i < 10; i++)
    {
        flower.base_x = i * 100;
        flower.stem_h = random(50,400);
        flower.col = color(
            random(0,255), 
            random(0,255),
            random(0,255)
            );
        flowers.push(flower);

    }
}
Carl__Che
  • 11
  • 2
  • 1
    Does this answer your question? [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – smac89 Jan 03 '20 at 05:23
  • See also https://stackoverflow.com/questions/39736397/is-this-a-good-way-to-clone-an-object-in-es6 – smac89 Jan 03 '20 at 05:23

2 Answers2

1

You can dereference the flower object before pushing into array by any of following three methods:

line flowers.push(flower); should be

flowers.push(Object.assign({}, flower));

OR

flowers.push({...flower});

OR

flowers.push(JSON.parse(JSON.stringify(flower)));
Geetanjali
  • 458
  • 3
  • 13
0

How about pushing distinct objects into the array, instead of changing the same object over and over again.

var flowers = [];

function setup() {
  createCanvas(1000, 500);
  base_x = width/2;
  base_y = height - 50;

  for (var i = 0; i < 10; i++) {
    // Creates a new object in every iteration.
    // And there's no point in defining this variable globally.
    var flower = {
      base_x: i * 100,
      base_y: height - 50,
      stem_h: random(50, 400),
      col: color(
        random(0, 255),
        random(0, 255),
        random(0, 255)
      )
    };

    flowers.push(flower);
  }
}

or even

var flowers = Array.from({length: 10}, function(_, i){
  return {
    base_x: i * 100,
    base_y: height - 50,
    stem_h: random(50, 400),
    col: color(
      random(0, 255),
      random(0, 255),
      random(0, 255)
    )
  };
});
Thomas
  • 11,958
  • 1
  • 14
  • 23